iOS 給項(xiàng)目添加CoreData

1、導(dǎo)入 CoreData 框架:

Build Phases -> Link Binary With Libraries -> 添加 CoreData.framework

2、添加 CoreData 模型:

File -> New -> File -> iOS -> Core Data -> Data Model -> XXX.xcdatamodeld

3、創(chuàng)建實(shí)體

XXX.xcdatamodeld -> Add Entity -> 添加對應(yīng)的 Attributes

4、自動創(chuàng)建實(shí)體關(guān)聯(lián)文件

創(chuàng)建好實(shí)體對象XXX.xcdatamodeld之后,右側(cè)屬性欄Code Generation下面的Language默認(rèn)為Swift,這里使用OC,就改成Objective-C;Codegen默認(rèn)為Class Definition,無需更改。通過XcodeBuild會自動生成對應(yīng)的實(shí)體關(guān)聯(lián)文件,但是這些文件不會在目錄中顯示出來,但對應(yīng)的格式為:

//格式
實(shí)體名(表名)+CoreDataClass.h
實(shí)體名(表名)+CoreDataClass.m
實(shí)體名(表名)+CoreDataProperties.h
實(shí)體名(表名)+CoreDataProperties.m
//例如,實(shí)體名(表名)為Video,對應(yīng)的關(guān)聯(lián)文件為:
Video+CoreDataClass.h
Video+CoreDataClass.m
Video+CoreDataProperties.h
Video+CoreDataProperties.m

使用對應(yīng)的實(shí)體時(shí),導(dǎo)入對應(yīng)的頭文件即可,例如:

#import "Video+CoreDataClass.h"

5、手動創(chuàng)建實(shí)體關(guān)聯(lián)文件

實(shí)體對象XXX.xcdatamodeld里面的Codegen一定得設(shè)置為Manual/None,否則報(bào)文件重復(fù)錯(cuò)誤,選中實(shí)體,點(diǎn)擊Editor,點(diǎn)擊Create NSManagedObject Subclass…生成實(shí)體關(guān)聯(lián)文件:

創(chuàng)建實(shí)體關(guān)聯(lián)文件

手動創(chuàng)建好關(guān)聯(lián)文件之后,目錄如下圖所示,用的時(shí)候?qū)雽?yīng)的Properties頭文件即可:
實(shí)體關(guān)聯(lián)文件

6、創(chuàng)建數(shù)據(jù)庫(例子)

//1、導(dǎo)入對應(yīng)實(shí)體
#import "Video+CoreDataProperties.h"
//2、創(chuàng)建上下文全局變量
@property (strong, nonatomic) NSManagedObjectContext *context;
//3、創(chuàng)建數(shù)據(jù)庫相關(guān)代碼
- (void)createDataBase  {
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
    NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *dbPath = [docPath stringByAppendingPathComponent:@"video.sqlite"];
    NSLog(@"dbPath = %@", dbPath);
    NSURL *dbURL = [NSURL fileURLWithPath:dbPath];
    NSError *error = nil;
    [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:dbURL options:nil error:&error];
    if (error) {
        NSLog(@"創(chuàng)建數(shù)據(jù)庫失敗");
    } else {
        NSLog(@"創(chuàng)建數(shù)據(jù)庫成功");
    }
    _context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    _context.persistentStoreCoordinator = store;
}

7、插入數(shù)據(jù)(例子)

- (void)insertData {
    Video *video = [NSEntityDescription insertNewObjectForEntityForName:@"Video" inManagedObjectContext:_context];
    video.name = @"山西老妖";
    video.url = @"http://video.winson.com.mp4";
    NSError *error = nil;
    if ([_context save:&error]) {
        NSLog(@"插入數(shù)據(jù)成功");
    } else {
        NSLog(@"插入數(shù)據(jù)失?。?@", error);
    }
}

8、新增表、增加字段之后的處理

項(xiàng)目中經(jīng)常有新業(yè)務(wù)會涉及到新增表、或者修改表結(jié)構(gòu)的操作,這個(gè)時(shí)候需要對模型對象XXX.xcdatamodeld進(jìn)行版本管理,主要包括兩個(gè)過程:創(chuàng)建新版本模型+數(shù)據(jù)遷移

  • 創(chuàng)建新版本模型:
    XXX.xcdatamodeld -> Editor -> Add Model Version... -> XXX2.xcdatamodeld
  • 指定新版本:
    XXX.xcdatamodeld -> 右側(cè)屬性欄 -> Model Version -> XXX2.xcdatamodeld
    XXX2.xcdatamodeld中修改后,重新編譯,到此,新的配置已經(jīng)完成,接下來,需要對數(shù)據(jù)進(jìn)行遷移。

9、數(shù)據(jù)遷移

Core Data自帶的輕量級的數(shù)據(jù)遷移Core Data手動創(chuàng)建Mapping文件進(jìn)行遷移

  • Core Data自帶的輕量級的數(shù)據(jù)遷移
NSDictionary *options = @{NSSQLitePragmasOption: @{@"journal_mode": @"DELETE"}, //禁用日志
                          NSMigratePersistentStoresAutomaticallyOption: @YES, //自動遷移
                          NSInferMappingModelAutomaticallyOption: @YES}; //自動創(chuàng)建遷移文件
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:dbURL options:options error:&error];
  • Core Data手動創(chuàng)建Mapping文件進(jìn)行遷移
    這種方式也要設(shè)置上面兩個(gè)參數(shù),只不過自己創(chuàng)建Mapping文件相對更靈活,更準(zhǔn)確,可以完成更為復(fù)雜的遷移操作:
    New File -> Core Data -> Mapping Model -> 選擇需要Mapping的源數(shù)據(jù)庫 -> 再選擇目標(biāo)數(shù)據(jù)庫 -> AAA.xcmappingmodel
    然后進(jìn)行Build操作,舊的數(shù)據(jù)將會按照Mapping文件的規(guī)則遷移到XXX2.xcdatamodeld

未完待續(xù)……

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容