开发者

Why is my retain method being called when a property accessor is being used

My object is not getting released from memory so I override retain method and put a breakpoint in to see where in c开发者_运维技巧ode it gets retained.

Every time the object is referenced using a property accessor the retain method is called. Why would this be happening?

color = self.myobject.color

calls retain.


The synthesized property accessor for retained properties looks something like this:

- (UIColor *)color
{
    return [[_color retain] autorelease];
}

Therefore, your retain method is called, but it's balanced with an autorelease.

See this code snippet in the Objective-C Programming Language Guide for an example of how a synthesized accessor might look (the locking part doesn't apply in the nonatomic case, but the retain-autorelease is the same).


Because you probably declared your property as retain or copy:

@property (nonatomic, retain) MyObject* myobject;

If you @synthesize that, the compiler will generate code that looks more or less like:

- (void) setMyobject: (MyObject *) value
{
    if (value != myobject)
    {
        [myobject release];
        myobject = value;
    }
}

Each time you assign to self.myobject, that method is invoked with the new object as value parameter. It should release the old object, but the last object added is retained. You'll have to release it in your dealloc. And you should release what you allocated, so the pattern is:

MyObject *myObj = [[MyObject alloc] init];
self.myobject = myObj;
[myObj release];

Items returned from a method are usually autoreleased, so you should not release those:

MyObject *myObj = [someOtherObject someMethod: 17];
self.myobject = myObj;
// Do NOT release myObj!

Update

See @omz's explanation. I misread and was talking about the setter. Your getter does a retain too, but that is immediately paired with an autorelease. Since you only log the retains, it only looks as if you have leaks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜