您的位置:首页 > 移动开发 > Objective-C

Objective-C程序设计第三章:类,对象和方法

2015-06-19 13:41 531 查看
这一章简单介绍了如何书写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

为什么要有setter, getter方法?

因为无法直接访问类的实例变量。

类的创建和方法调用:

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
4000
]);

}
return 0;
}

实例创建:类名 *实例 = [[类名 alloc] init];

类名 *实例 创建一个指针

[类名 alloc] 分配空间, init初始化内存空间

使用[实例名 方法名:参数]的方式调用实例方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息