iOS-Core Data基礎,ios-coredata基礎

來源:互聯網
上載者:User

iOS-Core Data基礎,ios-coredata基礎

Core Data基礎

Core Data是一個API集合,被設計用來簡化資料對象的持久儲存。

在此先不普及概念,先通過一個簡單的案例使用來感受一下Core Data的精妙之處。

在建立工程的時候勾選Use Core Data.

1 #import <UIKit/UIKit.h> 2 #import <CoreData/CoreData.h> 3 4 @interface AppDelegate : UIResponder <UIApplicationDelegate> 5 6 @property (strong, nonatomic) UIWindow *window; 7 8 @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext; 9 @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;10 @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;11 12 - (void)saveContext;13 - (NSURL *)applicationDocumentsDirectory;14 @endAppDelegate.h 1 #import "AppDelegate.h" 2 3 @interface AppDelegate () 4 5 @end 6 7 @implementation AppDelegate 8 9 10 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 11 // Override point for customization after application launch. 12 return YES; 13 } 14 15 - (void)applicationWillResignActive:(UIApplication *)application { 16 // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 17 // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 18 } 19 20 - (void)applicationDidEnterBackground:(UIApplication *)application { 21 // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 22 // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 23 } 24 25 - (void)applicationWillEnterForeground:(UIApplication *)application { 26 // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 27 } 28 29 - (void)applicationDidBecomeActive:(UIApplication *)application { 30 // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 31 } 32 33 - (void)applicationWillTerminate:(UIApplication *)application { 34 // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 35 // Saves changes in the application's managed object context before the application terminates. 36 [self saveContext]; 37 } 38 39 #pragma mark - Core Data stack 40 41 @synthesize managedObjectContext = _managedObjectContext; 42 @synthesize managedObjectModel = _managedObjectModel; 43 @synthesize persistentStoreCoordinator = _persistentStoreCoordinator; 44 45 - (NSURL *)applicationDocumentsDirectory { 46 // The directory the application uses to store the Core Data store file. This code uses a directory named "com.wyg.CoreDataDemo" in the application's documents directory. 47 return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 48 } 49 50 - (NSManagedObjectModel *)managedObjectModel { 51 // 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. 52 if (_managedObjectModel != nil) { 53 return _managedObjectModel; 54 } 55 NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreDataDemo" withExtension:@"momd"]; 56 _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; 57 return _managedObjectModel; 58 } 59 60 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 61 // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. 62 if (_persistentStoreCoordinator != nil) { 63 return _persistentStoreCoordinator; 64 } 65 66 // Create the coordinator and store 67 68 _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 69 NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataDemo.sqlite"]; 70 NSError *error = nil; 71 NSString *failureReason = @"There was an error creating or loading the application's saved data."; 72 if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { 73 // Report any error we got. 74 NSMutableDictionary *dict = [NSMutableDictionary dictionary]; 75 dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data"; 76 dict[NSLocalizedFailureReasonErrorKey] = failureReason; 77 dict[NSUnderlyingErrorKey] = error; 78 error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict]; 79 // Replace this with code to handle the error appropriately. 80 // 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. 81 NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 82 abort(); 83 } 84 85 return _persistentStoreCoordinator; 86 } 87 88 89 - (NSManagedObjectContext *)managedObjectContext { 90 // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) 91 if (_managedObjectContext != nil) { 92 return _managedObjectContext; 93 } 94 95 NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; 96 if (!coordinator) { 97 return nil; 98 } 99 _managedObjectContext = [[NSManagedObjectContext alloc] init];100 [_managedObjectContext setPersistentStoreCoordinator:coordinator];101 return _managedObjectContext;102 }103 104 #pragma mark - Core Data Saving support105 106 - (void)saveContext {107 NSManagedObjectContext *managedObjectContext = self.managedObjectContext;108 if (managedObjectContext != nil) {109 NSError *error = nil;110 if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {111 // Replace this implementation with code to handle the error appropriately.112 // 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.113 NSLog(@"Unresolved error %@, %@", error, [error userInfo]);114 abort();115 }116 }117 }118 119 @endAppDelegate.m

可能初次接觸感覺密密麻麻的,那我們暫且也不用管它,既然系統為我們自動產生,我們直接使用就行了。

現在我們點擊進去CoreDataDemo.xcdatamodeld這個檔案,我們可以看到下面的介面。

1 #import <Foundation/Foundation.h> 2 #import <CoreData/CoreData.h> 3 4 @class People; 5 6 @interface Book : NSManagedObject 7 8 @property (nonatomic, retain) NSNumber * name; 9 @property (nonatomic, retain) NSString * author;10 @property (nonatomic, retain) People *people;11 12 @endBook.h 1 #import "Book.h" 2 #import "People.h" 3 4 5 @implementation Book 6 7 @dynamic name; 8 @dynamic author; 9 @dynamic people;10 11 @endBook.m 1 #import <Foundation/Foundation.h> 2 #import <CoreData/CoreData.h> 3 4 5 @interface People : NSManagedObject 6 7 @property (nonatomic, retain) NSString * name; 8 @property (nonatomic, retain) NSNumber * age; 9 @property (nonatomic, retain) NSManagedObject *book;10 11 @endPeople.h 1 #import "People.h" 2 3 4 @implementation People 5 6 @dynamic name; 7 @dynamic age; 8 @dynamic book; 9 10 @endPeople.m

到現在為止,萬事俱備,只欠代碼了。

我們對Core Data的操作,無外乎增刪改查,直接上代碼

在AppDelegate啟動函數中,添加以下代碼是往Core Data中添加一條記錄:

1 //託管物件內容,有點類似於資料庫 2 NSManagedObjectContext *context = self.managedObjectContext; 3 //執行個體,有點類似於表,插入一條資料,並給對象屬性賦值 4 People *people = [NSEntityDescription insertNewObjectForEntityForName:@"People" inManagedObjectContext:context]; 5 people.name = @"wyg"; 6 7 Book *book =[NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:context]; 8 book.name = @"三國演義"; 9 10 people.book = book;11 12 [self saveContext];增 1 NSManagedObjectContext *context = self.managedObjectContext; 2 NSEntityDescription *entity = [NSEntityDescription entityForName:@"People" inManagedObjectContext:context]; 3 NSFetchRequest *request = [NSFetchRequest new]; 4 request.entity = entity; 5 NSArray *arr = [context executeFetchRequest:request error:nil]; 6 7 for (People *object in arr) 8 { 9 NSLog(@"%@,%@",object.name,object.book.name);10 }查

查得結果:

 概念普及Core Data的關鍵組件:資料存放區(data store),持久儲存協調器(Persistent Store Coordinator),託管物件模型(Managed Object Modeal),託管物件內容(Managed Object Context),這些術語可能難以理解,沒有關係,以後在實踐中我們會逐漸理解。1.資料存放區:資料存放區是儲存資料的一個或一組檔案。當訊息發送到Core Data,實際寫入到了磁碟檔案。建立資料存放區依賴建立資料存放區是的參數,資料存放區可以是一個二進位檔案,一個SQLite資料庫,或者記憶體中的資料檔案。2.持久儲存協調器:持久儲存協調器是NSPersistentStoreCoordinator的執行個體,扮演上下文和資料存放區的中間角色,協調器從上下文中獲得資料請求並將他們轉寄給合適的資料存放區。3.託管物件模型:NSManagedObjectModel的執行個體,模型是一組實體,定義了應用程式中的資料對象。4.託管物件內容:NSManagedObjectContext執行個體,用於儲存所有管理的資料對象。可以將上下文想想成儲存所有應用程式資料的沙箱,可以在上下文中添加對象,刪除對象,以及修改等。     

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.