在上下文崩溃时保存在Core Data中

时间:2013-11-23 08:28:06

标签: ios objective-c sqlite core-data ios7

我有一个创建单独线程的方法:

// Create thread
dispatch_queue_t uniqueQueue = dispatch_queue_create("Unique Email Queue", NULL);

// Run block on another thread called downloadQueue
dispatch_async(uniqueQueue, ^{

        // Get the persistance store coordinator
        AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
        self.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator;

        // Setup the managed object context
        NSManagedObjectContext *managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];

        // Save to core data for redundancy
        User *coreDataUser = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:self.managedObjectContext];

        coreDataUser.username = [emailStr lowercaseString];
        coreDataUser.email = emailStr;
        coreDataUser.name = nameStr;

        NSError *error;

        if (![managedObjectContext save:&error])
        {
            NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
        }            
    }

应用程序总是崩溃在这一行:

User *coreDataUser = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:self.managedObjectContext];

我使用本教程作为参考:http://www.codigator.com/tutorials/ios-core-data-tutorial-with-example/

我的AppDelegate.m文件包含:

- (NSManagedObjectModel *)managedObjectModel {
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    _managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];

    return _managedObjectModel;
}

//3
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil)
    {
        return _persistentStoreCoordinator;
    }

    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"HappyPeople.sqlite"]];

    NSError *error = nil;

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error])
    {
        /*Error for store creation should be handled in here*/
    }

    return _persistentStoreCoordinator;
}

- (NSString *)applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

我错过了什么?

另外,我如何查看数据库中的数据?

0 个答案:

没有答案