views:

288

answers:

4

Hello

I currently have an array of strings, I'm getting a NSString object from this array by calling the -componentsJoinedByString: method. Example:

NSString *someString = [[NSString alloc] initWithString: [myStrings componentsJoinedByString:@","];

Since -componentsJoinedByString: returns me an NSString, I'm assuming that it is not "owned" by me, therefore what I just did should be ok? or do I have to do this:

NSString *toDelete = [myStrings componentsJoinedByString:@","];

NSString *someString = [[NSString alloc] initWithString:toDelete];
[toDelete release];

Help with clarifying this is much appreciated!

A: 

You only need to retain the string returned by componentsJoinedByString: it if it will be used outside the current method's scope.

dreamlax
+4  A: 

The first example you wrote is correct, although in practice it would be clearer just to write NSString *someString = [[myStrings componentsJoinedByString:@","] copy]; (note that this will be retained, so you will have to release it at some point in the future.

If you're having trouble with memory management, this page might help. It's not too hard to learn the rules, but you're going to run into a lot of problems until you do.

Marc Charbonneau
A: 

Marc answered the first part while I was typing.

The second set of expressions you have is not required and is bad practice; You are sending a release message to the string toDelete which you do not own. You are declaring a pointer to the the string, but did not alloc the memory for the string being pointed to (nor did you call retain on it) so you don't own the object that toDelete is pointing to.

Abizern
A: 

Do you need to make use of this string later outside of this method? If so, you probably want to assign it to an instance variable, so do this:

someStringIVar = [[myStrings componentsJoinedByString:@","] copy];

Otherwise, if it's for temporary use within the method only, do this:

NSString *someString = [myStrings componentsJoinedByString:@","];

Either way, there is absolutely no need for the ridiculous -initWithString: and +stringWithString: calls that people seem far too keen on.

Mike Abdullah