关闭

[Objective-C] alloc和init要嵌套写而不要分开写

888人阅读 评论(0) 收藏 举报

转自:

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html#//apple_ref/doc/uid/TP40011210-CH4


下面的写法是不建议的

NSObject* someObject = [NSObject alloc];
[someObject init];

建议的做法是

NSObject* someObject = [[NSObject alloc] init];


因为,[NSObject alloc] 的返回值和 [someObject init] 的返回值未必是同一个值。如果不一致,对 someObject 发送message,就相当于于找错对象了,并且这个对象有可能是没有被初始化过的


有些 class factory 方法可以替代这里的 alloc/init 嵌套做法,用一个方法把二者都做了,效果和先 alloc 紧接着 alloc 是一样的,比如:

NSNumber *magicNumber = [NSNumber numberWithInt:42];


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


原文如下:

Note: It’s possible for init to return a different object than was created by alloc, so it’s best practice to nest the calls as shown.

Never initialize an object without reassigning any pointer to that object. As an example, don’t do this:

    NSObject *someObject = [NSObject alloc];
    [someObject init];
If the call to init returns some other object, you’ll be left with a pointer to the object that was originally allocated but never initialized.

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2722962次
    • 积分:23670
    • 等级:
    • 排名:第274名
    • 原创:158篇
    • 转载:596篇
    • 译文:0篇
    • 评论:202条
    最新评论