views:

29

answers:

2

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?

+2  A: 

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.

Yuji
Thank you for the reply, I also thought it's autoreleased. but as I ran the code with 'leak' instrument, it shows that there are leaks with this array. what could be the problem?
boreas
That depends on what you wrote in "..." above. Post more code. Or, run the static analyzer. Look for the menu "Build and Analyze". That should come before using the Leak instrument.
Yuji
I'm still quite new to objective-C and part of the ... is not written by me.so there is a loop using for(NSString* strPh in wordLiterals),and inside the loop strPh is sometimes initiated again using [strPh initWithString: [[resultMap objectAtIndex:0] objectForKey:@"mapping"]]; where resultMap is the result from a sqlite query.this strPh is also set as an attribute of another instance with [pf setEntry:strPh];I hope this is sufficient for you to point out my error.
boreas
It's a very bad idea in Objective-C to re-initialize an `NSString` by `initWithString`. Don't. Always use `[[NSString alloc] init...]`. And then, you need to balance that with a `release`, as the ownership policy dictates. How did you define the property? Did you make it as a `(nonatomic, retain)` property? There are many points involved.
Yuji
Thank you for pointing that out. Now I have released all allocs and it's working fine.
boreas
A: 

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.

walkytalky