1.在创建工程时未添加CoreData,后期想要使用CoreData则要在工程Appdelegate.h文件中添加CoreData库和CoreData中的通道类(用来管理类实例和CoreData之间的所有操作)和保存到CoreData文件的方法.
2.添加完这些后去创建.xcdatamodeld文件
3.填写创建文件的名称(建议与工程名字一致后面添加CoreData)
4.文件创建完成后就可以像以前一样去创建对应实体文件和添加实体的属性了.
5.添加完实体后生成对应的实体类文件
6.创建完对应的实体类文件后回到Appdelegate.m中去实现添加的方法和实例
1.首先在Appdelegate.m的- (void)applicationWillTerminate:(UIApplication *)application;中调用下保存的方法. - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. [self saveContext]; } 2.然后实现通道类和保存的方法. #pragma mark - Core Data stack @synthesize persistentContainer = _persistentContainer; - (NSPersistentContainer *)persistentContainer { // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. @synchronized (self) { if (_persistentContainer == nil) { _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"LotterSelectCoreData"]; [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) { if (error != nil) { // 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. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ NSLog(@"Unresolved error %@, %@", error, error.userInfo); abort(); } }]; } } return _persistentContainer; } #pragma mark - Core Data Saving support - (void)saveContext { NSManagedObjectContext *context = self.persistentContainer.viewContext; NSError *error = nil; if ([context hasChanges] && ![context save:&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. NSLog(@"Unresolved error %@, %@", error, error.userInfo); abort(); } }
7.至于新版Xcode 中coredata的使用在下篇博文中会有介绍.