如何在CoreData中添加SQLite作为持久存储?

时间:2010-01-08 06:22:01

标签: iphone objective-c core-data

在使用核心数据概念的目标中,我们需要将分裂创建为持久存储,否则它将自动创建?

1 个答案:

答案 0 :(得分:5)

在Xcode中创建新的iPhone应用程序项目时,大多数模板都允许“使用核心数据进行存储”选项。选中此选项后,应用程序委托将包含一些样板核心数据代码,包括打开和/或创建持久存储的块:

/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

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

    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"App.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.
         */
        //NSLog(@"Error with persistent store %@, %@", error, [error userInfo]);
        NSLog(@"Error with persistent store (did the data model change?)");
        abort();
    }

    return persistentStoreCoordinator;
}