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

465 views Asked by At

I have initialized an delegate object in ViewDidLoad of my ViewController, but when I am again loading it, it is initializing the value again.

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?

4

There are 4 answers

1
Di Wu On BEST ANSWER

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.

4
Max On

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

0
Kendall Helmstetter Gelner On

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.

0
JeremyP On

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]];