シングルトンパターンが気に入らない場合は、アプリ全体であなたのコンテキストへの参照を渡すことができます。あなたのアプリケーション内のすべてのビューコントローラは、次のビューコントローラに渡すことができるように、コンテキストへの参照を保持する必要があります。初期化子でコンテキストを渡すことも、プロパティを使用することもできます。
// Example class interface. All of your view controllers would look like this.
// You could put this stuff in a protocol as well.
@interface ViewController : UIViewController
{
@property (nonatomic, strong) NSManagedObjectContext *context
// or
- (instancetype)initWithContext:(NSManagedObjectContext *)context;
}
アプリケーションが開始すると、あなたのNSManagedObjectContext
をロードし、それらを初期化してかprepareForSegue
のいずれかで、画面上に来るすべてのビューコントローラにそれを渡す必要があります。コードを使用してアプリを起動する場合は、AppDelegate
で初期化することができます。または、初期ビューコントローラのviewDidLoad
にロードすることができます。これは、AppDelegate
の例です。
- application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSManagedObjectContext *context = // get your context
// initialize your view controller or get it from the storyboard or put this code where ever your app starts
ViewController *viewController = [[ViewController alloc] initWithContext:context];
// or pass the context as a property
ViewController *viewController = [[ViewController alloc] init];
viewController.context = context;
window.rootViewController = viewController;
[window makeKeyAndVisible];
return YES;
}