这一章简单介绍了如何书写Objective-C的类,对象和方法
类的声明:
@interface Computer: NSObject
使用interface关键字,而不是传统面向对象的class。
在头文件中声明类,向其中加入方法和属性。
实例方法用 - 开头
类方法用 + 开头
俩个方法的区别:
1.类别符号不同
2.实例方法可以用实例变量, 类方法不可以用实例变量
#import <Foundation/Foundation.h>
@interface Computer : NSObject
{
NSString *kaka;
int number;
}
- (void)setDoc: (NSString *)docContent;
- (void)printDoc;
- (NSString *)getDoc;
- (void)setMovie: (NSString *)movieName;
- (NSString *)getMovie;
- (void)playMovie;
+ (void)helloComputer;
@end
类的定义(又叫实现):
#import "Computer.h"
@implementation Computer
{
NSString *doc;
NSString *movie;
}
- (void)setDoc: (NSString *)docContent{
doc = docContent;
}
- (void)printDoc{
NSLog(@"The doc %@ is printing...", doc);
}
- (NSString *)getDoc{
return doc;
}
- (void)setMovie: (NSString *)movieName{
movie = movieName;
}
- (NSString *)getMovie{
return movie;
}
- (void)playMovie{
NSLog(@"We are watching movie %@", movie);
}
+ (void)helloComputer{
NSLog(@"Computer say 'hello' to you");
}
@end
因为无法直接访问类的实例变量。
类的创建和方法调用:
int main(int argc, const char * argv[]) {
@autoreleasepool {
[Computer helloComputer];
Computer *computer = [[Computer alloc] init];
[computer setDoc:@"真好玩"];
//[computer printDoc];
NSLog(@"I'm printing the doc %@", [computer getDoc]);
[computer setMovie:@"异形大战铁血战士"];
// [computer playMovie];
NSLog(@"I'm watch movie %@", [computer getMovie]);
}
return 0;
}
实例创建:类名 *实例 = [[类名 alloc] init];
类名 *实例 创建一个指针
[类名 alloc] 分配空间, init初始化内存空间
使用[实例名 方法名:参数]的方式调用实例方法。