PDA

View Full Version : Who Owns This Object?




shusseina
Mar 26, 2009, 08:37 AM
If method1 has the following line of code, does method1 then own the object (and therefore need to release it)?

NSString *EOL = @"\n";

If the above code is legal, why would anyone use either of these two alternatives?

NSString *EOL;
EOL = [[NSString alloc] init];
EOL = @"\n";

or

NSString *EOL;
EOL = [NSString stringWithString:@"\n"];

Thanks



lee1210
Mar 26, 2009, 08:46 AM
NSString *EOL = @"\n";


NSString literals live forever. No one needs to release or autorelease them.


If the above code is legal, why would anyone use either of these two alternatives?

NSString *EOL;
EOL = [[NSString alloc] init];
EOL = @"\n";

They would not, as assigning the string literal changes the address, so you're leaking memory because you no longer have a pointer to the Object created in the second line.


or

NSString *EOL;
EOL = [NSString stringWithString:@"\n"];

It seems unlikely that someone would do this... but obviously the method is there, so you can do it. You have the power to control the lifetime of EOL now, but you still have the NSString literal that will live forever, so the benefits are negligible.

-Lee