开发者

how can I allocate and initialize an object, so it should not reload again when ViewDidLoad Loads?

开发者 https://www.devze.com 2023-02-08 18:47 出处:网络
I have initialized an delegate object in ViewDidLoad of my ViewController, but when I am again loading it, it is initializing the value aga开发者_如何学Cin.

I have initialized an delegate object in ViewDidLoad of my ViewController, but when I am again loading it, it is initializing the value aga开发者_如何学Cin.

I am saving some some sort of array in that delegate object which I want to access using getObject and setObject. What should I do so that the delegate object doesn't get re-initialized every time ViewDidLoad is called?


Have you considered this strategy:

  • After your app is launched, before that specific object is initialized and used, set it to nil.
  • For the first time your app is trying to use it, check if it's still nil (it should since it's the first time), then initialize it and use it
  • For the rest of your app's life cycle, whenever your app runs into the viewDidLoad method again, always check whether that object is nil or not (it should not be nil at this point). This would save your app the time and efforts trying to initialize an object which was already initialized.

However, when you use this strategy, you should be aware that that specific object's value should stay the same throughout your app's life cycle. Otherwise it won't work.


You should initialize only UI elements in viewDidLoad. Everything else should be inited in constructor (initWith...)


If you want someplace that things are only done once, that's generally in a Singleton somewhere - an object that is made once, and referenced from all over.

The AppDelegate is a default singleton you get for free. But if you decide after a while too much is going in the AppDelegate, it's a good idea to make different Singleton objects into which you put custom data.

There are many examples all over showing how to make a Singleton, now that you know the term you are looking for.


As everybody else is saying, you probably need a singleton object. The easiest way to do this is like so:

// interface

@interface MyViewController
{ ... }

+(DelegateType*) theDelegate;

...

@end

// implementation

@implementation MyViewController

+(DelegateType*) theDelegate
{
    static DelegateType* theDelegate = nil;

    if (theDelegate == nil)
    {
        theDelegate = [[DelegateType alloc] init];
    }
    return theDelegate;
}

@end

// To use it 

    [foo setDelegate: [MyViewController theDelegate]];
0

精彩评论

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

关注公众号