开发者

Do I need to retain parameters passed to custom initWith method?

开发者 https://www.devze.com 2023-03-01 01:31 出处:网络
for example: in interface: 开发者_如何转开发@property(retain) NSObject* anObject; in interface, in implemetation:

for example:

in interface:

开发者_如何转开发@property(retain) NSObject* anObject;

in interface, in implemetation:

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


Yes, as you cannot guarantee that 'another' lifetime will be the same as lifetime of the object you create you need to ensure that by retaining it in init method (and do not forget to release it in dealloc method). So the following is correct:

...
if(self = [super init]){
     anObject = [another retain];
}
...

One more thing - by defining retaining property for anObject you say that you take an ownership of that object and thus you must release it in dealloc method. If you don't retain 'another' parameter in init method it will be eventually released (either in dealloc or in setter method) without being retained - so your application may crash with EXEC_BAD_ACCESS error.


I think it's a good practice to do

self.anObject = another;

but it's the same

0

精彩评论

暂无评论...
验证码 换一张
取 消