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的使用在下篇博文中會有介紹.