1

I am creating an iOS app that uses core data in almost every VC.

The app has many Navigation Controller and different types of segues.

I want all these viewControllers to be using the same Managed object context. Also, I do not want to keep using prepare to segue to do this as I can use that to pass more relevant info for a particular VC.

Hence, I need help to create a central class or something similar that will help me get the same instance of the managed object context in all my VCs.

madLokesh
  • 1,860
  • 23
  • 49
Pratham Mehta
  • 293
  • 2
  • 13

1 Answers1

2

Singleton Pattern!

@class SingleTonnedClass;
@interface SingleTonnedClass : NSObject
   + (SingleTonnedClass*)sharedInstance;
   - (id)getterInstanceMethod;
   .
   .
   .
@end

In .m

@implementation SingleTonnedClass
  SingleTonnedClass *singleTonInstance;
  + (SingleTonnedClass*)sharedInstance
    {
       if(!singleTonInstance)
       {
         singleTonInstance = [SingleTonnedClass new];
       }
    }

  ...
  .
  .
  other method implementation
@end

From anywhere in your project you can access the instance of SingleTon class by just including its header and,

  [SingleTonnedClass shatedInstance]; //will return you the singleton instance

and access methods like this

 [[SingleTonnedClass sharedInstance]someMethod];
egghese
  • 2,193
  • 16
  • 26