アプリデリゲートからビューコントローラーにコンテキストを渡す際に問題が発生します。私はインターネット上で多くのチュートリアルを見つけました、そしてすべてdidFinishLaunchingWithOptions
がビューコントローラを作成し、コンテキストプロパティを設定してそれをプッシュするためにメソッドを使用することを提案します。私の問題は、ストーリーボードを使用したいのですが、ビューコントローラーが作成され、アプリデリゲートではなく、ストーリーボード内にプッシュされます。
私は自分のアプリデリゲートでこれを実行しようとしました:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//instantiate local context
NSManagedObjectContext *context = [self managedObjectContext];
if (!context)
{
// Handle the error.
NSLog(@"Error: Context is null");
}
//reference the view controller
helloCoreDataViewController1_001 *rootViewController = [helloCoreDataViewController1_001 alloc];
// Pass the managed object context to the view controller
rootViewController.managedObjectContext = context;
return YES;
}
そしてこれは私のビューコントローラで:
@implementation helloCoreDataViewController1_001
@synthesize name, address, phone, status, managedObjectContext;
//....
- (IBAction)saveContact
{
NSLog(@"name: %@",self.name.text);
NSLog(@"address: %@",self.address.text);
NSLog(@"phone: %@",self.phone.text);
//Save the new instance of the contact entity
Contact *contact = (Contact *)[NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:managedObjectContext];
[contact setContactName:[NSString stringWithFormat:@"%@",self.name.text]];
[contact setValue:self.address.text forKey:@"address"];
[contact setContactPhone:[NSString stringWithFormat:@"%@",self.phone.text]];
NSError *error = nil;
if (![managedObjectContext save:&error])
{
// Handle the error.
NSLog(@"error: %@", error.description);
self.status.text = @"Error: contact NOT saved";
}
else
self.status.text = @"Contact saved";
}
デバッグすると、アプリデリゲートでコンテキストが正しく入力され、ViewControllerのプロパティも正常であることがわかります。しかし、私のsaveContact
メソッドが呼び出されると、コンテキストは空になります。
これについて何か提案はありますか?ストーリーボードを使用してコンテキストをViewControllerに渡すにはどうすればよいですか?