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

来源:互联网 发布:苏30mki和歼11 知乎 编辑:程序博客网 时间:2024/06/05 09:42

转自:

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
原创粉丝点击