views:

34

answers:

2

Hello

For NSString, we can use

  1. NSString *str = [[NSString alloc] initWithString:@"hi"]

  2. NSString *str = [NSString stringWithString:@"hi"];

  3. NSString *str = @"hi";

Can someone pls told me in the form of point 3, whether str own @"hi"? I mean whether I need to [str release] when clean up?

Thanks

for point 1, yes, I need; for point 2, no, I don't

For point 3?

+3  A: 

No, you don't need to release it.

String literal (that's what you have in case 3) are created in compile time and their lifetime is the lifetime of your application. You can also easily check that release/retain operations do not affect their retain count (try to NSLog retainCount property and you'll see that)

Vladimir
+2  A: 

Taking each case and applying the standard memory management rules:

  1. You used an +alloc method, therefore you own this object. You must release or autorelease it.
  2. You did not use +alloc, +new or -copy methods. You do not own this object, so your code shouldn't release it.
  3. The same as 2 - you didn't allocate or copy this object, you don't own it, you shouldn't release it.

Notice that rather than treating string literals as magic objects, if you treat them in exactly the same way as any other object and apply exactly the same rules regarding ownership and memory management, your code will work.

Graham Lee