Hi,

On Mar 24, 2008, at 11:19 PM, Samvel wrote:

Lots of classes define static methods that create objects for instance:

Class NSString:
        +(id) stringWithString: (NSString *) string;

or Class NSArray:
        +(id) arrayWithObjects: (id) firstObj, ...;

A minor nit-pick about terminology: these methods are not called "static methods" in Objective-C. They are "class methods".


I am really confused about next situation and memory management of objects created via those methods. Please, explain.
Imagine class with

        NSString *string;

instance variable. I create it and initiate with method above in:
        -(id) init;

of my class. Now, want to use this string in another method sometime later, say in:
        -(void) plug;

Should I retain string in init?

Yes. By convention, the class methods you refer to -- known as convenience methods -- return autoreleased objects. That means that, if you don't do anything to keep them around, they will be released automatically at some future time. When exactly is an implementation detail, but you can only rely on them lasting until the current call stack returns out of your code.

Since your object needs the string referred to by its instance variable to last for a a different period of time, it needs to retain the string to guarantee that.


e.g.:

        -(id) init
        {
          // ...
          string = [NSString stringWithString: @"hello"];
          [string retain];
          // ...
        }

That's one way of doing it. Another way would be for the init method to call your setter for that property (if one exists). Since the setter should already have proper memory management, you won't have to worry about this as a separate case.



        -(void) dealloc
        {
          // ...
          [string dealloc];
          // ...
        }

The above is wrong. You should never explicitly invoke "dealloc" on an object (except doing [super dealloc] as part of your own dealloc implementation). When your object is deallocated, it doesn't know that the string should also be deallocated. It just knows that it doesn't need the string to stick around anymore. (Something else might need the string.) So, your object should just release the string.

Cheers,
Ken
_______________________________________________

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