AppDelegate.hまず、次のようなプロパティを作成する必要があります。
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext; // or strong if you ARC instead of retain
を使用readonlyすると、コンテキストを外部から変更できなくなります。
次のようにAppDelegate.m合成します。
@synthesize managedObjectContext;
常にAppDelegate.mオーバーライド内で次のようなgetterメソッド
- (NSManagedObjectContext *)managedObjectContext
{
if (managedObjectContext != nil) return managedObjectContext;
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext;
}
完了すると、managedObjectContextどこからでもアクセスできるプロパティがあります。
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext* context = appDelegate.managedObjectContext;
よりクールなアプローチはAppDelegate.h、次のようにクラスメソッドを作成することです。
+ (AppDelegate *)sharedAppDelegate;
次にAppDelegate.m、次のようにします。
+ (AppDelegate *)sharedAppDelegate
{
return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
AppDelegateこれで、どこでも、ヘッダー( )をインポートする前に#import "AppDelegate.h"、次のことができます。
AppDelegate* appDelegate = [AppDelegate sharedAppDelegate];
NSManagedObjectContext* context = appDelegate.managedObjectContext;
ノート
このようなアプローチを使用すると、アプリケーションが厳格になります。この問題を克服するために、MarcusZarraによるiPhoneでのnsmanagedobjectcontext-on-the-iphoneの受け渡しについて読むことをお勧めします。
それが役に立てば幸い。