Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

shusseina

macrumors newbie
Original poster
Feb 23, 2009
14
0
If method1 has the following line of code, does method1 then own the object (and therefore need to release it)?

Code:
NSString *EOL = @"\n";

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

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

or

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

Thanks
 
Code:
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?

Code:
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

Code:
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
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.