Search code examples
iphoneobjective-cinitviewdidloadalloc

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


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?


Solution

  • 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.