LoginSignup
42
41

More than 5 years have passed since last update.

CoreDataの使い方メモ

Last updated at Posted at 2014-02-15

[モデル]→取得→[Entity]
この流れを簡単にするのがCoreDataFrameworkです。

#import<CoreData/CoreData.h>

した上でEntityにするクラスを作っておく。ちなみに
こいつは、NSManagedObjectクラスを親として継承していなければ
ならない。

Entity.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>


@interface Entity : NSManagedObject

@property (nonatomic, retain) NSDate * deadline;
@property (nonatomic, retain) NSString * homeWork;
@property (nonatomic, retain) NSNumber * isExistAssign;
@property (nonatomic, retain) NSString * labelA;
@property (nonatomic, retain) NSString * labelB;
@property (nonatomic, retain) NSNumber * tag;

@end

一方

Entity.m
#import "Entity.h"
@implementation Entity
@dynamic deadline;
@dynamic homeWork;
@dynamic isExistAssign;
@dynamic labelA;
@dynamic labelB;
@dynamic tag;
@end

こんな感じ。@dynamicてなんじゃってなったら

ことの運び方は
[モデル]→[エンティティ]
ラップしたエンティティを変更したりしなかったりしたあと、
Contextに突っ込んで実際のモデルに反映する。

ちなみに、とりあえずDB(Store)はsqliteを利用するので、作ってあげないとだめ。

ex
- (NSURL*)createStoreURL {
    NSArray *directories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[directories lastObject] stringByAppendingPathComponent:DB_NAME];
    NSURL *storeURL = [NSURL fileURLWithPath:path];
    return storeURL;
}

もちろんStore内につっこむモデルも

ex
- (NSURL*)createModelURL {
    NSBundle *mainBundle = [NSBundle mainBundle];
    NSString *path = [mainBundle pathForResource:MODEL_NAME ofType:@"momd"];
    NSURL *modelURL = [NSURL fileURLWithPath:path];
    return modelURL;
}

んで、NSManagedObjectModelと、ストアの実体NSPersistentScoreCoodinator,あとNSManagedObjectContextもつくる。

ex.m
- (NSManagedObjectContext*)createManagedObjectContext {
    NSURL *modelURL = [self createModelURL];
    NSURL *storeURL = [self createStoreURL];
    NSError *error = nil;
    NSManagedObjectModel *managedObjectModel=[[NSManagedObjectModel alloc]initWithContentsOfURL:modelURL];
    NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
    [persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
    NSManagedObjectContext *managedObjectContent = [[NSManagedObjectContext alloc] init];
    [managedObjectContent setPersistentStoreCoordinator:persistentStoreCoordinator];
    return managedObjectContent;
}

んで、Entityを新規に作成してコンテキストにつっこむのはこんなん。

ex

    Entity* newObject = [NSEntityDescription insertNewObjectForEntityForName:ENTITY_NAME inManagedObjectContext:context];

//newObjectに変化くわえーの

    NSError *error = nil;
    if([context save:&error]/*daoにflushするみたいな*/) {
       //セーブ成功した処理
    } else {
        //セーブに失敗したときの処理
    }


んじゃ逆にStoreから指定したオブジェクトを取得するには。

ex

 NSEntityDescription *entity = [NSEntityDescription entityForName:ENTITY_NAME inManagedObjectContext:context];

    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    //取ってくるエンティティの設定を行う
    [request setEntity:entity];

    //検索条件の設定を行う。Add Predicate as filter;
    NSString *searchString = [searchWindows text];
    //比較対象を直接描くのがポイント
    NSPredicate *predicate =[NSPredicate predicateWithFormat:@"labelA == %@",searchString];
                              [request setPredicate:predicate];

    NSError *error = nil;

    //データのフェッチを行う Data Fetching.
    NSArray *fetchResults = [context executeFetchRequest:request error:&error];

    if([fetchResults count] > 0) {
        NSMutableString *str = [NSMutableString stringWithFormat:@"Found %d Datas \n",[fetchResults count]];
        int i = 0;
        for (Entity *ent in fetchResults) {
            [str appendFormat:@"Num:%d Room:%@ Name:%@ isAss:\n",i,ent.labelA,ent.labelB];
            i++;
        }

        dataViewer.text = str;

    } else {
        dataViewer.text = @"Data is None!";
    }


以上

ここにCoreDataの簡単なSampleみたいなの置きました。多分使えます←

42
41
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
42
41