简体   繁体   中英

iOS potential leak of an objects property

I'm switching from ARC to MRC now because I take an old project. However I'm not familiar with MRC, now when I analyse my code , there is a potential leak of an objects property.

here is the code

@property (nonatomic, retain) NSString *string;
@property (nonatomic, retain) AnotherObject *anotherObject;
- (id)init{
    ...
    _string = [[NSSting alloc] init];
    ...
}

- (void)doThings{
    self.anotherObject.text = self.string; // text is also a retain property of anotherObject,and anotherObject is also a property
}

- (void)dealloc{
   [_string release];
   [_anotherObject release];
   ...
}

I try to fix it , so I make _string an autorelease object

- (id)init{
    ...
    _string = [[[NSSting alloc] init]autorelease];
    ...
}

and still release _string in the dealloc method, It works and when I analyze my code again ,the potential leak disappeared.

But I can't figure out why, could someone explain it for me?? thank you very much.

The correct pattern is the one you originally tried. Assign your ivar without an autorelease in init , like:

_string = [[NSString alloc] init];

and release it in dealloc like:

[_string release];

If you use the property's setter you need to use autorelease, because the property (being declared with retain ) will retain the object you assign to it. So if you assign your string property with self.string = ... then it should look like:

self.string = [[[NSString alloc] init] autorelease];

In your question you said that the static analyzer picked up the error. If you look at the static analyzer messages in the issues tab in Xcode, you can actually expand the analysis issue and Xcode will show you the code paths the analyzer took to see the potential leak. That can really help with tracking down these sorts of issues. 在此处输入图片说明

In your initialize method you are allocating your string. So it means your variable is the owner of the object. But when its work has been completed still it is retaining the object. So in that case you are getting potential leak warning.

But after you put autorelease, So it is releasing the object when work has been completed. So your potential leak has been disappeared.

Autorelease just removes a retain count from the object it does not "free" the memory immediately like in c. When the autorelease pool ends all auto released objects with a count of 0 will have their memory freed up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM