Core data 使用CoreData实现数据持久化

Core data 使用CoreData实现数据持久化,core-data,ios5,data-persistence,Core Data,Ios5,Data Persistence,大家好,我在使用CoreData持久性时遇到了一个问题,我的问题是,当我启动我的应用程序时,我设法将应用程序中的表单中的一些数据添加到我的数据库中,并使用NSLog显示它们。 但实际上,我认为当我停止ipad模拟器并在之后重新启动它时,所有这些数据都会消失 所以我真的不知道它是来自我的代码还是因为模拟器。 我制作了一个图表,向您展示我的应用程序和实体的体系结构: 问题是我使用的是不同的viewController,所以我需要将ManagedObjectModel传递给每个人。我的表单位于newD

大家好,我在使用CoreData持久性时遇到了一个问题,我的问题是,当我启动我的应用程序时,我设法将应用程序中的表单中的一些数据添加到我的数据库中,并使用NSLog显示它们。 但实际上,我认为当我停止ipad模拟器并在之后重新启动它时,所有这些数据都会消失

所以我真的不知道它是来自我的代码还是因为模拟器。 我制作了一个图表,向您展示我的应用程序和实体的体系结构:

问题是我使用的是不同的viewController,所以我需要将ManagedObjectModel传递给每个人。我的表单位于newDocumentViewController中,当我添加somme实体时,我希望在所有其他viewController中访问它们并将其保存到应用程序本地存储

下面是一些代码向您展示:

AppDelegate.m

@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.

    DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    UINavigationController *detailNavigationController = [[UINavigationController alloc] initWithRootViewController:detailViewController];

    MasterViewController *masterViewController = [[MasterViewController alloc] initWithNibName:@"MasterViewController" bundle:nil];
    UINavigationController *masterNavigationController = [[UINavigationController alloc] initWithRootViewController:masterViewController];

    masterViewController.managedObjectContext = self.managedObjectContext;    
    detailViewController.managedObjectContext = self.managedObjectContext;
我在每个masterViewController和DetailViewController中都有这些属性,从DetailViewController到NewDocumenViewController都有这些属性来接收objectContext

@property (nonatomic,strong) NSManagedObjectContext *managedObjectContext;
因此,我真的不知道如何从每个控制器访问我的数据,数据是否通过如下方式存储在本地:

NewDocumentController.m

-(void) addNewDocument:(NSString*)name with_niveau:(NSInteger)level{
    Document *doc = [NSEntityDescription insertNewObjectForEntityForName:@"Document" inManagedObjectContext:managedObjectContext];
    doc.nom=name;
    doc.niveau=[NSNumber numberWithInteger:level];
}
-(void) addNewDocument_info:(NSString*)name with_createur:(NSString*)createur with_dateModif:(NSDate*)date1 with_status:(BOOL)etat{

    DocumentInfo *doc_info = [NSEntityDescription insertNewObjectForEntityForName:@"DocumentInfo" inManagedObjectContext:managedObjectContext];

    doc_info.nom =name;
    doc_info.createur=createur;
    doc_info.date_creation=[NSDate date];
    doc_info.date_modification=date1;
    doc_info.status= [NSNumber numberWithBool:etat];
}

您需要保存数据:

NSError *error = nil;
[self.managedObjectContext save:&error];