Cocoaの日々(旧)
Core Data その1
CoreDataは永続性スタックと呼ばれるいくつかのクラスで構成されていて、利用時にはこれらのインスタンスを用意する必要がある。
(過去記事から引用)

コードはこんな感じ(とりあえず awakeFromNib に書いてみた)。
- (void)awakeFromNib
{
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[NSManagedObjectModel mergedModelFromBundles:nil]];
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator:persistentStoreCoordinator];
NSError* error = nil;
NSString* filepath = [NSString stringWithFormat:@"%@/%@",
[NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0],
@"memo.db"];
[persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:[NSURL fileURLWithPath:filepath]
options:nil
error:&error];
NSLog(@"1:%@", error);
NSManagedObject* memo =
[NSEntityDescription insertNewObjectForEntityForName:@"Memo"
inManagedObjectContext:managedObjectContext];
[memo setValue:@"hello" forKey:@"title"];
[memo setValue:@"photo1.png" forKey:@"photo"];
[managedObjectContext save:&error];
NSLog(@"2:%@", error);
}
永続性スタックである NSPersistentStoreCoordinator, NSManagedObjectContext を用意し、必要な処理を加えていけば良い。以前の記事でも解説されているが、前者はモデル(いわゆるスキーマ)と(persistent object storeを通じて)DBファイルを扱い、後者はDBに対する検索、追加、変更、削除などのプログラミングのインターフェイスを提供している。今回永続化タイプは SQLite を選んだ。
モデルは Xcodeの「新規ファイル...」から作成できる。

今回は Memo というエンティティを1つ用意した。

さて実行してみよう。所定の場所に memo.db が作成されて(サンプルコードで挿入した)値が格納されているのがわかる。

0 件のコメント:
コメントを投稿