Objective-C 语法二(对象初始化)
2017-07-02 18:35
369 查看
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]; } @end int 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]; } @end int 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]; } @end int 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; }
相关文章推荐
- Objective-C边学边记-14:对象初始化
- Objective-C 学习笔记 - part 3 - 为对象分配内存并初始化
- Objective-C语法之集合对象的那些事儿(九)
- Objective-C 编程语言(3) 定义类---分配并初始化对象,init方法的返回值,初始化方法的实现
- 谈谈Objective-C下对象的初始化
- C# 3.0--对象初始化语法
- Objective-C语法之数组对象的那些事儿
- Objective-C语法之集合对象的那些事儿(九)
- Objective-C语法之词典对象的那些事儿(八)
- LHF Objective-C语法(4)对象初始化
- Objective-C 2.0 with Cocoa Foundation--- 7,对象的初始化以及实例变量的作用域
- Objective-C 2.0 with Cocoa Foundation---对象的初始化以及实例变量的作用域(2)
- Objective-C 2.0 with Cocoa Foundation---对象的初始化以及实例变量的作用域(3)
- Objective-C语法之集合对象的那些事儿(九)
- Objective-C语法之数组对象的那些事儿(七)
- Objective-C 2.0 with Cocoa Foundation--- 7,对象的初始化以及实例变量的作用域
- Objective-C 2.0 with Cocoa Foundation---对象的初始化以及实例变量的作用域(1)
- Objective-C语法之Object对象的那些事儿(五)
- Objective-C语法之数组对象的那些事儿(七)
- objective-c中的构造函数(对象初始化)(七)