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

转自:

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.

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

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

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭