Reputation: 1061
How can I release an array created from a parameter?
I have function like
-(NSMutableArray*)composePhrase:(NSString*) phraseLiteral{
...
NSArray* wordLiterals=[phraseLiteral componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[]"]];
...
[wordLiterals release];
}
and I always got problem with this release. Can anyone tell me how to make it right?
Upvotes: 0
Views: 175
Reputation: 9543
The array returned by componentsSeparatedByCharactersInSet:...
is autoreleased. This is true of pretty much all objects created like this -- ie, not via alloc
or copy
.
You are expected to retain
it yourself if you want to keep hold of it. Otherwise it will evaporate at some unspecified future time (or if it doesn't it's not your responsibility).
Calling release
on something you don't own will inevitably lead to grief down the line, so don't do it. In this case, since you seem to be using it only within the same scope, you can just let it take care of itself.
Upvotes: 0
Reputation: 34185
You need to understand the Object Ownership Policy.
You only gain the ownership automatically when the method name contains alloc
, new
or copy
. Here, componentsSperatedByCharactersInSet:
does not. Therefore, the returned wordLiterals
is not owned by you. It's autoreleased. You shouldn't release
it. It's released automatically when the autorelease pool is drained when the current event loop is complete.
If you want to keep the object, you retain
it. Then you own it. When you no longer needs it, you release
it.
Upvotes: 2