Core Data主要分成三個部分
- Managed Object Context
- Persistent Store Coordinator
- Persistent Object Store
Managed Object Context這類別記載了我們的App在記憶體中所有的Entity,當你要求Core Data載入物件時,你必須先向Managed Object Context提出要求。
…假如不存在記憶體中的話,它會向Persistent Store Coordinator發出請求,試著嘗試尋找它。
Persistent Store Coordinator的任務是追蹤Persistent Object Store,而Persistent Object Store實際知道如何讀寫資料。
Managed Object Model則是用來處理資料的,這些元件都知道要如何處理資料。
整個流程大致上如下圖:
**Step 1.**建立Empty Application,專案名稱為core data example
記得要將Use Core Data打勾。
Step 2. 編輯core_data_sample.xcdatamodeld
首先開啟core_data_sample.xcdatamodeld這個檔案,點選中間下方的Add Entity,並輸入Phone(註:第一個字要大寫),接著在右邊可以找到Attributes,點選+加號,加入兩個屬性分別為name、number,其型態分別為String
、Integer 32。
**Step 3.**建立Phone.m、Phone.h
點選專案資料夾,右鍵➔New File。
選擇iOS➔Core Data➔NSManagedObject subclass,接著都直接下一步。
接著可以在專案的資料夾內會出現Phone.m、Phone.h
在這兩個檔案可看到裡面的變數都是跟xcdatamodeld內的有相關連的
Phone.h1 2 3 4 5 6 7 8 9
| #import <Foundation/Foundation.h> #import <CoreData/CoreData.h>
@interface Phone : NSManagedObject
@property (nonatomic, retain) NSString * name; @property (nonatomic, retain) NSNumber * number;
@end
|
這邊的@dynamic主要是告知 compiler 不要產生setter、getter,而是由程式本身來實作甚至是直到 Runtime 時以 Dynamic Loading 方式連結。
Phone.m1 2 3 4 5 6 7 8
| #import "Phone.h"
@implementation Phone
@dynamic name; @dynamic number;
@end
|
Step .4編輯AppDelegate.m
在該檔案內自行新增一個creatData方法
AppDelegate.m1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| -(void)creatData{ NSManagedObjectContext *context = [self managedObjectContext]; Phone *detail = [NSEntityDescription insertNewObjectForEntityForName:@"Phone" inManagedObjectContext:context]; detail.name = @"Mary"; detail.number = [NSNumber numberWithInt:323232123];
NSError *error; if(![context save:&error]){ NSLog(@"error"); } NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Phone" inManagedObjectContext:context]; [request setEntity:entity]; NSArray *array = [context executeFetchRequest:request error:&error]; for (Phone *pho in array) { NSLog(@"Name: %@", pho.name); NSLog(@"Number: %@", pho.number); } }
|
AppDelegate.m1 2 3 4 5 6 7 8
| - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [self creatData]; self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; }
|
最後編譯後,可以在Debug的地方看到NSLog的訊息。
參考資料:
- iPhone Core Data 1 - Intro
- @synthesize vs @dynamic, what are the differences?
- The Objective-C Programming Guide 入門筆記
- iPhone开发之CoreData(基础篇)