關於Core Data的一些整理(一),coredata整理

來源:互聯網
上載者:User

關於Core Data的一些整理(一),coredata整理
關於Core Data的一些整理(一)

在Xcode7.2中只有Mast-Debug和Single View中可以勾選Use Core Data

如果勾選了Use Core Data,Xcode會自動在AppDelegate中幫你產生Core Data的核心代碼,並且自動產生 .xcdatamodeld資料檔案 
  1 //Appdelegate.h中  2 #import <UIKit/UIKit.h>  3 #import <CoreData/CoreData.h>  4   5 @interface AppDelegate : UIResponder <UIApplicationDelegate>  6   7 @property (strong, nonatomic) UIWindow *window;  8   9 @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext; 10 @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel; 11 @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator; 12  13 - (void)saveContext; 14 - (NSURL *)applicationDocumentsDirectory; 15  16  17 @end 18  19  20  21 //Appdelegate.m中系統協助產生的程式碼 22 - (void)applicationWillTerminate:(UIApplication *)application { 23   // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 24   // Saves changes in the application's managed object context before the application terminates. 25   [self saveContext]; 26 } 27  28 #pragma mark - Core Data stack 29  30 @synthesize managedObjectContext = _managedObjectContext; 31 @synthesize managedObjectModel = _managedObjectModel; 32 @synthesize persistentStoreCoordinator = _persistentStoreCoordinator; 33  34 - (NSURL *)applicationDocumentsDirectory { 35     // The directory the application uses to store the Core Data store file. This code uses a directory named "qq100858433.JMHitList" in the application's documents directory. 36     return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 37 } 38  39 - (NSManagedObjectModel *)managedObjectModel { 40     // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model. 41     if (_managedObjectModel != nil) { 42         return _managedObjectModel; 43     } 44     NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"JMHitList" withExtension:@"momd"]; 45     _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; 46     return _managedObjectModel; 47 } 48  49 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 50     // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. 51     if (_persistentStoreCoordinator != nil) { 52         return _persistentStoreCoordinator; 53     } 54      55     // Create the coordinator and store 56      57     _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 58     NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"JMHitList.sqlite"]; 59     NSError *error = nil; 60     NSString *failureReason = @"There was an error creating or loading the application's saved data."; 61     if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { 62         // Report any error we got. 63         NSMutableDictionary *dict = [NSMutableDictionary dictionary]; 64         dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data"; 65         dict[NSLocalizedFailureReasonErrorKey] = failureReason; 66         dict[NSUnderlyingErrorKey] = error; 67         error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict]; 68         // Replace this with code to handle the error appropriately. 69         // 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. 70         NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 71         abort(); 72     } 73      74     return _persistentStoreCoordinator; 75 } 76  77  78 - (NSManagedObjectContext *)managedObjectContext { 79     // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) 80     if (_managedObjectContext != nil) { 81         return _managedObjectContext; 82     } 83      84     NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; 85     if (!coordinator) { 86         return nil; 87     } 88     _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; 89     [_managedObjectContext setPersistentStoreCoordinator:coordinator]; 90     return _managedObjectContext; 91 } 92  93 #pragma mark - Core Data Saving support 94  95 - (void)saveContext { 96     NSManagedObjectContext *managedObjectContext = self.managedObjectContext; 97     if (managedObjectContext != nil) { 98         NSError *error = nil; 99         if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {100             // Replace this implementation with code to handle the error appropriately.101             // 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.102             NSLog(@"Unresolved error %@, %@", error, [error userInfo]);103             abort();104         }105     }106 }107 108 @end

假如你在.xcdatamodeld中產生了如下實體和實體屬性:

 

那麼在VC中擷取資料庫內容和添加資料庫內容的代碼如下:
 1   //從Core Data中獲得已有資料 2   id appDelegate = [UIApplication sharedApplication].delegate; 3   NSManagedObjectContext *managedContext = [appDelegate managedObjectContext]; 4   NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"]; 5   @try { 6     self.people = [NSMutableArray arrayWithArray:[managedContext executeFetchRequest:fetchRequest error:nil]]; 7   } 8   @catch (NSException *exception) { 9     NSLog(@"Could not fetch %@", [exception userInfo]);10   }11   @finally {12     NSLog(@"Fetch Successful");13   }14   15   //為資料庫添加實體執行個體16   id appDelegate = [UIApplication sharedApplication].delegate;17   //NSManagedObjectContext可以看做記憶體中用來處理managedObjects的暫存器18   NSManagedObjectContext *mangedContext = [appDelegate managedObjectContext];19   //下面兩種方法都可以獲得Person實體20 //  NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:mangedContext];21 //  NSManagedObject *person = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:mangedContext];22 //  [person setValue:name forKey:@"name"];23   NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:mangedContext];24   [person setValue:name forKey:@"name"];25   @try {26     [mangedContext save:nil];27     [self.people addObject:person];28   }29   @catch (NSException *exception) {30     NSLog(@"Could not save %@", [exception userInfo]);31   }32   @finally {33     NSLog(@"Save Successfullt!");34   }

 

   

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.