Help us understand the problem. What is going on with this article?

CoreDataの使い方メモ

More than 5 years have passed since last update.

[モデル]→取得→[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みたいなの置きました。多分使えます←

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした