简体   繁体   中英

retain object in objective-c

I'm doing a set method:

OBS: somobject is an attribute of a class.

– (void)setSomeObject:(SomeObject *)newSomeobject {

    [someobject autorelease];

    someobject = [newSomeobject retain];

    return;

}

on [somobject autorelease] I declare that I don't want more to own the object under the scope of setSomeObject.

Does the "someobject" retained by another object will be released? Or the object will be released just on setSomeObject method?

If the someobject class atribute already exists?

What will be the behavior of this object?

I'd rename the parameter in the method so that it's different from the ivar:

– (void)setSomeObject:(SomeObject *)newObject 
{
    [someobject autorelease];

    someobject = [newObject retain];
}

Also you should read Apple docs for memory management and @property and @synthesize .

You have a significant problem, in that it seems you have two variables (the method parameter and an instance variable) with the same name. The compiler (and readers of this question, for that matter) can't tell to which you're referring.

For your memory management problems, check out Apple's programming guide.

What you need to accomplish in a setter is:

  1. Release any old object
  2. Retain the new object
  3. Assign the new object to your instance variable

Of course, if you do it literally in that order, you risk releasing the object too soon in the case where old & new objects are the same. That's where the "autorelease" comes in handy, because it schedules the object to be released, but only after your method returns.

Naming the method parameter & instance variable the same is (IMHO) confusing, and will give you a compiler warning, but if you absolutely insist on doing it that way, you can use "self->" to specify that you're referring to the instance variable:

– (void)setSomeObject:(SomeObject *)someobject {

[self->someobject autorelease];

self->someobject = [someobject retain];

return;

}

Finally, unless your setter method has to do something special, you should consider using @synthesize to have your setter/getter automatically generated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM