开发者

CoreData Save Permanently?

I have been working with Core Data in an iPad app and I can successfully save and fetch data inside the app. However when completely closing the application, fully, quit, take it out of multitasking, and that data disappears.

So does Core Data in anyway keep this data anywhere when the app is closed? Or do I need to look somewhere else?

EDIT: This is in the app delegate didFinishLaunchingWithOptions: [[[UIApplication sharedApplication] delegate] managedObjectContext]; and then I have this: context_ = [(prototypeAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; in the UIView subclass.

This is the NSPersistentStoreCoordinator code premade in the app delegate:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator_ != nil) {
        return persistentStoreCoordinator_;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"prototype.sqlite"];

    NSError *error = nil;
    persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.

         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.


         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

         * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
         [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

         */
        NSLog(@"Unresolved e开发者_运维问答rror %@, %@", error, [error userInfo]);
        abort();
    }    

    return persistentStoreCoordinator_;
}

So far I am using this to fetch data:

    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    NSEntityDescription *testEntity = [NSEntityDescription entityForName:@"DatedText" inManagedObjectContext:context_];
    [fetch setEntity:testEntity];
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"dateSaved == %@", datePicker.date];
    [fetch setPredicate:pred];

    NSError *fetchError = nil;
    NSArray *fetchedObjs = [context_ executeFetchRequest:fetch error:&fetchError];
    if (fetchError != nil) {
        NSLog(@"fetchError = %@, details = %@",fetchError,fetchError.userInfo);
    }
    noteTextView.text = [[fetchedObjs objectAtIndex:0] valueForKey:@"savedText"];

And this to save data:

NSManagedObject *newDatedText;
    newDatedText = [NSEntityDescription insertNewObjectForEntityForName:@"DatedText" inManagedObjectContext:context_];
    [newDatedText setValue:noteTextView.text forKey:@"savedText"];
    [newDatedText setValue:datePicker.date forKey:@"dateSaved"];

    NSError *saveError = nil;
    [context_ save:&saveError];
    if (saveError != nil) {
        NSLog(@"[%@ saveContext] Error saving context: Error = %@, details = %@",[self class], saveError,saveError.userInfo);
    }


Do you save the context in the right places? It is a common mistake not to save the context when entering background application state only in willTerminate.

Save the context in the following appdelegate method:

-(void)applicationDidEnterBackground:(UIApplication *)application

You are saving your context directly after inserting the object, this should be sufficient. Check the sqlite file in simulator if it contains any data after saving.

if

noteTextView.text = [[fetchedObjs objectAtIndex:0] valueForKey:@"savedText"];

does not throw an exception, there is an object found in context. Maybe it does not contain the expected value? Log the returned object from your fetchrequest to console to see if this might be the case


You should post the code that sets up your NSPersistentStoreCoordinator and adds your NSPersistentStore. By any chance are you using NSInMemoryStoreType as the type of your store? Because that would result in the behavior you're seeing. Alternately, you could be using a different path to the store each time, which would give you a fresh store each time. In general, your store should be in your Documents folder, and it should be given the same name on every launch. It should also use the NSSQLiteStoreType


I have discovered the problem. It turns out that due to its use of UIDatePicker, at the start of the program it set that date picker to today using:

NSDate *now = [[NSDate alloc] init];
[datePicker setDate:now];

So without using this it works perfectly. So currently I am looking for a solution to this issue, as this line seems to cause the problem.

UIDatePicker Interfering with CoreData


If you add a CoreData after create your project.There is a risk to make mistake in lazy_init your NSManagedObject.

-(NSManagedObjectContext*) managedObjectContext{
if (!_managedObjectContext) {
    _managedObjectContext =[self createManageObjectContextWithName:@"name.sqlite"];
}
return _managedObjectContext;}

Here is the right way:

- (NSManagedObjectContext *)managedObjectContext {
if (_managedObjectContext != nil) {
    return _managedObjectContext;
}

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
    return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜