On Tue, Mar 25, 2008 at 12:19 AM, Samvel <[EMAIL PROTECTED]> 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, ...;
>
> I am really confused about next situation and memory management of
> objects created via those methods. Please, explain.


These methods don't have +alloc, +new, or -copy in their names, so it's your
responsibility to retain the returned object if you're going to need it
later.


> 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?
> e.g.:
>
>        -(id) init
>        {
>          // ...
>          string = [NSString stringWithString: @"hello"];
>          [string retain];
>          // ...
>        }
>
>        -(void) dealloc
>        {
>          // ...
>          [string dealloc];
>          // ...
>        }


Retaining "string" is required here - you created it with a method named
+stringWithString:, and you need to use it later.

But, I wouldn't assign directly to the variable, nor would I place the call
to -retain in your -init method. That's fragile - think about what happens
if you want to assign a new  value to string from elsewhere in your code.
You'd have to remember how your -init method first created it, release the
old value, and also remember to retain the new value, because -dealloc will
eventually release it. That breaks encapsulation; why should you have to be
thinking about what's inside your -init method, when you're writing a -foo
method? And you'd have to repeat this every time you assigned a new value,
leaving retains and releases scattered through your code - forget just one
of them, and you'll have a difficult bug to find.

Instead, I would create a setter method:

- (void)setString:(NSString *)value {
    if (string != value) {
        [string release];
        string = [value copy];
    }
}

And, in your -init, and anywhere else you need to assign a new value to
string, just do this: [self setString:[NSString
stringWithString:@"string"]].

Now, your retain and release calls are grouped in one place, making it very
simple to verify that they're balanced properly.

sherm--
_______________________________________________

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