It depends on the lifetime of w (which is an NSString*?) is supposed to live.
If you have:
        void foo() {
                NSString* w = [NSString stringWithFormat:@"something %i", x];
                bar(w);
        }
Then the answer is: You do not have to retain w (the above code is correct without "release" and incorrect if you add "release").

If you have:
        NSString* w = NULL;
        void foo() {
                w = [NSString stringWithFormat:@"something %i", x];
                [w retain];
        }
        void baz() {
                bar(w);
                [w release];
                w = nil;
        }
        Then the answer is: Yes - you will have to add retain.

The reason is that any object created in the way that you show (NSString stringWithFormat) is autoreleased. This means that it is guaranteed to be live until the autorelease pool is drained next (and you cannot add another release without first adding a retain). Unless your code explicitly creates and destroys autorelease pools, this again means that the object is guaranteed to be alive within your function scope. Once you return it may be deleted at any time. Therefore if you need the object to stay alive across function scopes, you must manage the life time (and add retain/release). Objects created by [[Class [alloc] init] have already been retained for you, and you should make sure that you release, or autorelease. When in doubt, add a retain/release pair. For example, the following is also correct (barring any NSExceptions):
        void foo() {
                NSString* w = [[NSString stringWithFormat:@"something %i", x] 
retain];
                bar(w);
                [w release];
        }

If you are uncertain about memory management, be sure to run with the "Leaks" tool frequently and also run with debugmalloc (also know that obj-c 2 has a garbage collection option).

Jesper Storm Bache


On Oct 23, 2008, at 10:24 PM, Ron Green wrote:

If I call NSString w = [NSString stringWithFormat:@"something %i", x];

Am I now suppose to call retain on w?
When I'm done I know I'm suppose to release w.
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/jsbache%40adobe.com

This email sent to [EMAIL PROTECTED]

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to