Objective-C 语法二(对象初始化)
来源:互联网 发布:在github上下载源码 编辑:程序博客网 时间:2024/05/29 16:25
Objective-C 语法二(对象初始化)
首先申明下,本文为笔者学习《Objective-C 基础教程》的笔记,并加入笔者自己的理解和归纳总结。
1、创建对象。
两种方法创建对象,这两种方法是等价的。- [类名 new];
- [[类名 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;}
阅读全文
0 0
- Objective-C 语法二(对象初始化)
- LHF Objective-C语法(4)对象初始化
- objective-c对象初始化
- Objective-C对象初始化
- Objective-C基础教程六(对象初始化)
- objective-c 语法 细节(二)
- Objective-C基础语法(二)
- Objective-C对象之初始化和两段构造法(二)
- Objective-C对象之初始化和两段构造法(二)
- Objective-C对象初始化小结
- 【Objective-C基础】对象初始化
- Objective-C对象初始化简要
- Objective C 面向对象编程(二)
- objective-c中的构造函数(对象初始化)(七)
- objective-c中的构造函数(对象初始化)(七)
- objective-c中的构造函数(对象初始化)(七)
- iOS学习(六)Objective-C 对象的初始化
- objective-c 编程基础(3.1 对象初始化)
- CDN(内容分发网络)技术原理
- hadoop之map读取数据流程
- ros catkin_make 出现add_custom_target cannot create target 错误
- TCP三次握手连接及seq和ack号的正确理解
- BZOJ 3622 已经没有什么好害怕的了
- Objective-C 语法二(对象初始化)
- PKI系统深入介绍
- twitter工程师的一点经验
- 程序员必读书籍书单
- C++综合系列之模拟栈模版(数组版及单链表版)
- Objective-C 语法三(属性值)
- 获取当前显示的viewController
- C++ STL系列(一)简介
- 服务器上无权限源代码MySQL安装