开发者

Question about releasing object with @property @synthesize

开发者 https://www.devze.com 2023-03-28 09:41 出处:网络
I know many similar questions have been asked, which is why I hesitated to post this at all, but I couldn\'t find anything that answered my question exactly:

I know many similar questions have been asked, which is why I hesitated to post this at all, but I couldn't find anything that answered my question exactly:

When I use @property and @synthesize, does @synthesize take care of releasing the original value for the object being set? I.e. if I have:

@interface SomeClass:NSObject
{
    NSObject *object;
}

@property (nonatomic, retain) NSObject *object;
@end

@implementation SomeClass
@开发者_运维问答synthesize object;
@end

Is this equivalent to getting a setter method that looks like this?

-(void)setObject:(NSObject *)newObject
{
[object release];
object = [newObject retain];
}

Or do I have to somehow take care of releasing the original object myself?

Thanks for the clarification!


The answer is yes. Setter and getter are generated for you and are well done to keep you away from memory management:

-(void)setObject:(NSObject *)newObject {
  if (object != newObject) {
    [object release];
    object = [newObject retain];
  }
}

To release your object you can call:

[self setObject:nil];


No need to release the original object yourself, however, you need to still clean things up in -dealloc.

0

精彩评论

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

关注公众号