如何知道managedObjectContext在另一个视图控制器中被更改

时间:2012-05-31 15:56:16

标签: iphone core-data

我在这里关注核心数据教程。我们有RootViewcontroller和addRecipeViewController。

我列出了一些类和一些函数以及下面的流程屏幕,以便您不会迷路


Recipe.h
#import <CoreData/CoreData.h>
@interface Recipes :  NSManagedObject  
{
}
@property (nonatomic, retain) NSString * recipeName;
@property (nonatomic, retain) NSString * cookingTime;

@end

addRecipeViewController.h
@class Recipes;

@interface AddRecipeViewController : UIViewController <UITextFieldDelegate> {
    Recipes *recipes;
    UITextField *textFieldOne;
    UITextField *textFieldTwo;
}

addRecipeViewController.m
    - (void)save {
        1.recipes.recipeName = textFieldOne.text;
        2.recipes.cookingTime = textFieldTwo.text;
        3.NSError *error = nil;
        4.if (![recipes.managedObjectContext save:&error]) {
            // Handle error
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            exit(-1);  // Fail
        }   
        [self dismissModalViewControllerAnimated:YES];
    } 

RootViewController.m

- (void)insertNewObject {
    AddRecipeViewController *addRecipeView = [[AddRecipeViewController alloc] initWithNibName:@"AddRecipeViewController" bundle:[NSBundle mainBundle]];
    Recipes *recipes = (Recipes *)[NSEntityDescription insertNewObjectForEntityForName:@"Recipes" inManagedObjectContext:self.managedObjectContext];
    addRecipeView.recipes = recipes;
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: addRecipeView];
    [self.navigationController presentModalViewController:navController animated:YES];
    [addRecipeView release];
}

图片流程: enter image description here


点击addRecipeViewController的事件Save后,它会将recipes保存到managedObjectContext。 rootViewConroller迟早会使用managedObjectContext

NSFetchedResultsController检索数据

问题:我不明白所有视图控制器manageObjectContext的相同之处是什么,以便您在添加或manageObjectContext后获得最新的rootViewControllerRecipe

中的manageObjectContext删除addRecipeViewController

请帮助我理解这个问题。

欢迎所有评论。

2 个答案:

答案 0 :(得分:1)

managedObjectContext基本上是您的持久层,它包含一个缓存和一种检索尚未在缓存中的对象的方法。您希望避免在应用程序中使用多个托管对象上下文,这样您就不需要处理令人讨厌的缓存同步问题。

所以我不确定你遇到的问题是什么导致你暂停,但请不要过分复杂化问题。核心数据非常好,可以为您提供持久性存储的单一入口点,并为您保持所有内容的同步,因此您应该使用它:)

另外,请务必不要混淆NSManagedObjectContextNSManagedObject。托管对象存在于上下文中。它们不是一回事。

答案 1 :(得分:0)

您可能希望在上下文中发生更改时收到通知。如果是这样,请阅读:Are there Core Data call back methods?