我是否需要保留传递给自定义initWith方法的参数?

Car*_*loS 3 memory-management objective-c

例如:

在界面中:

@property(retain) NSObject* anObject;
Run Code Online (Sandbox Code Playgroud)

在界面中,在实现中:

-(id)initWithAnotherObject:(NSObject*)another{
    if(self = [super init]){
         anObject = another;    //should this be anObject = [another retain]?
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*mir 6

是的,因为您无法保证"另一个"生命周期与您创建的对象的生命周期相同,您需要确保将其保留在init方法中(并且不要忘记在dealloc方法中释放它).所以以下是正确的:

...
if(self = [super init]){
     anObject = [another retain];
}
...
Run Code Online (Sandbox Code Playgroud)

还有一件事 - 通过为anObject定义保留属性,你说你拥有该对象的所有权,因此你必须在dealloc方法中释放它.如果你没有在init方法中保留'another'参数,它将最终被释放(在dealloc或setter方法中)而不被保留 - 因此你的应用程序可能会因EXEC_BAD_ACCESS错误而崩溃.