ObjC-Why it is incorrect when implement [alloc] and [init] methods separatly? [duplicate]

我的梦境 提交于 2019-12-31 06:17:47

问题


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.

Actually, this is a example in Apple's ObjC document, but i'm not quite clear with this, that is, why NSObject *someObject = [[NSObject alloc] init] can promise return the object we just needed, while NSObject *someObject = [NSObject alloc]; [someObject init]; can not?


回答1:


Just because -init could return something different from someObject. In your example you have to re-assign the pointer to the result of the -init.



来源:https://stackoverflow.com/questions/13301365/objc-why-it-is-incorrect-when-implement-alloc-and-init-methods-separatly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!