开发者

Do I need to 'retain' when storing an existing object in a controller instance variable?

I'm fairly new to Objective-C and am trying to get to grips with the complex world or memory management.

I'm building an iPhone app and have a global singleton object that is used by various view controllers.

I'm trying to shorten the code I have to write each time I开发者_如何学运维 access this global object and want to store a reference to this object as an instance variable in the view controllers.

My view controller .h file:

@interface MyViewController : UIViewController {

    MyGlobalObjectType *_myobject;
}

@end

This is my init method of my view controller .m file:

-(id)initWithCoder:(NSCoder *)aDecoder
{
    if ((self = [super initWithCoder:aDecoder])) {        
        _myobject = [[Global sharedGlobal] myobject];
    }
    return self;    
}

My question is when I store a reference (pointer) to another variable do I have to call retain on it when initialising that instance variable?


In general, no. Memory management with a singleton object can be a tricky thing to get right, but usually, you want the singleton to be initialized once throughout the course of the application and not deallocated until the application quits.

In this case, when your object (inside the singleton) gets initialized, it has a reference count of +1. If you were to call retain on that object, its reference count would go up to +2. This is a perfectly okay thing to do as long as you remember to call release on it when your view controller is done with it, bringing its count back down to +1. That said, you usually don't need to do this.

In other words, remember that it is the object that has the reference count. Pointers to the object do not, so there's no need to send a retain message in order to keep this object alive.


Why would you want to hold a reference to your singleton? That defeats the purpose of creating one in the first place. Just get a reference to singleton at the moment you need it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜