Objective C interface(objective什么意思)
在Objective C里面,interface基本可以理解为其他语言里面的class。
当然也有些不同。
首先我们可以新建一个Objective-C的file。
这里我们添加一个MyClass.m和一个MyClass.h文件。
使用@interface 来定义一个类,使用@implementation来写实现。
MyClass.h
#import <Foundation/Foundation.h>
@interface MyClass : NSObject
- (void) hello;
@end
MyClass.m
#import "MyClass.h"
#import <Foundation/Foundation.h>
@implementation MyClass
- (void) hello {
NSLog(@"HelloWorld");
return;
}
@end
这里定义了一个方法hello,没有输入参数,也没有返回值,答应log "HelloWorld"。
#import用于引入头文件,和C的#include类似,只是#import本身可以保证相同的文件只被包含一次。不用像C语言一样,使用宏来控制头文件引入一次。
主程序如下:
#import <Foundation/Foundation.h>
#import "MyClass.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
MyClass *myClass = [[MyClass alloc] init];
[myClass hello];
}
return 0;
}
使用alloc和init方法来构造MyClass的一个实例。调用myClass的hello方法来输出"HelloWorld"。在Objective-C里面成为发送一个hello消息。
运行结果如下。
这是一个基本的@interface,只包含了一个方法。