Objective-C 语法二(对象初始化)

来源:互联网 发布:在github上下载源码 编辑:程序博客网 时间:2024/05/29 16:25

Objective-C 语法二(对象初始化)

首先申明下,本文为笔者学习《Objective-C 基础教程》的笔记,并加入笔者自己的理解和归纳总结。

1、创建对象。

两种方法创建对象,这两种方法是等价的。
  • [类名 new];
  • [[类名 alloc] init];
alloc方法分配内存,init方法初始化对象。

2、初始化方法init。

init方法中,调用[super init]方法,并更新self。如果self为nil,则初始化失败。最后返回self。
@interface Shape : NSObject {int width;int height;}@end@implementation Shape - (id) init {if (self = [super init]) {width = 20;height = 20;NSLog(@"Shape init");}return self;}- (NSString*) description {return [NSString stringWithFormat: @"(%d, %d)", width, height];}@endint main(int argc, const char* argv[]) {@autoreleasepool {Shape* shape = [[Shape alloc] init];NSLog(@"%@", shape);}return 0;}

3、自定义初始化方法。

Shape有两个属性,使用initWithWidth: height方法,在初始化时定义width和height属性。init方法也可以调用该方法初始化。
@interface Shape : NSObject {int width;int height;}@end@implementation Shape - (id) init {if (self = [self initWithWidth: 20 height: 20]) {}return self;}- (id) initWithWidth: (int)w height: (int)h {if (self = [super init]) {width = w;height = h;}return self;}- (NSString*) description {return [NSString stringWithFormat: @"(%d, %d)", width, height];}@endint main(int argc, const char* argv[]) {@autoreleasepool {Shape* shape = [[Shape alloc] init];NSLog(@"%@", shape);shape = [[Shape alloc] initWithWidth: 100 height: 100];NSLog(@"%@", shape);}return 0;}

4、子类自定义初始化方法。

Rectangle类继承Shape,但四个边角可以是圆弧型的,radius代表四个角的弧长。
@interface Rectangle : Shape {int radius;}- (void) setRadius: (int)radius;@end@implementation Rectangle- (id) initWithWidth: (int)w height: (int)h {if (self = [super initWithWidth: w height: h]) {radius = 10;}return self;}- (void) setRadius: (int)r {radius = r;}- (NSString*) description {return [NSString stringWithFormat: @"(%d, %d) radius = %d",width, height, radius];}@endint main(int argc, const char* argv[]) {@autoreleasepool {Rectangle* rect = [[Rectangle alloc] init];NSLog(@"%@", rect);rect = [[Rectangle alloc] initWithWidth: 100 height: 100];[rect setRadius: 20];NSLog(@"%@", rect);}return 0;}