欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS Coredata的基本使用

程序员文章站 2022-06-24 20:42:30
ios coredata的基本使用 coredata 管理类:nsmanagedobjectmodel、nspersistentstorecoordinator、nsmanagedobjectcon...

ios coredata的基本使用

coredata 管理类:nsmanagedobjectmodel、nspersistentstorecoordinator、nsmanagedobjectcontext。其中,nsmanagedobjectmodel是模型管理类,管理app中的数据模型;nspersistentstorecoordinator将model和持久化存储联系起来,并且将上下文(nsmanagedobjectcontext)与持久化存储联系起来,其实就是充当解析器。nsmanagedobjectcontext是上下文类,负责管理数据的获取、创建和保存等工作。

coreda创建

(1)创建工程时,勾选“use core data”选项
iOS Coredata的基本使用

(2)在工程中选择新建文件,在新建文件界面选择新建“data model”, 点击next即可新建
iOS Coredata的基本使用

-coredata创建数据模型
进入刚建好的数据库中,如下图点击“add entity”增加一个数据模型,双击该entity进行重命名。点击2,在数据表中增加一个属性,双击该属性进行重命名,并且指定type类型。
iOS Coredata的基本使用
点击“style”,可以看到数据库中所有数据表的关系图。
iOS Coredata的基本使用

注:ios8之后,nsmanagedobjectmodel对nsmanagedobject统一管理,不需要再次创建subclass,在使用时,直接引入#import “entity名称+coredataproperties.h”头文件即可。

-创建appdatamanager单例,管理数据表增删改查等基本操作。
(1)声明nsmanagedobjectcontext、nsmanagedobjectmodel、nspersistentstorecoordinator为实体变量,并实现初始化方法:

@interface appdatamanager() {
    nsmanagedobjectcontext *objcontext;
    nsmanagedobjectmodel *objmodel;
    nspersistentstorecoordinator *persistentcoordinator;
}

@end

static appdatamanager *sharedinstance = nil;

@implementation appdatamanager

+ (instancetype)sharedinstance {
    static dispatch_once_t oncetoken;
    dispatch_once(&oncetoken, ^{
        sharedinstance = [[appdatamanager alloc] init];
    });
    return sharedinstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self createobjmodel];
        [self createpersistentcoordinator];
        [self createobjcontext];
    }
    return self;
}

- (void)createobjmodel {
    if (!objmodel) {
        objmodel = [nsmanagedobjectmodel mergedmodelfrombundles:nil];
    }
}

- (void)createpersistentcoordinator {
    if (persistentcoordinator != nil) {
        return;
    }
    persistentcoordinator = [[nspersistentstorecoordinator alloc] initwithmanagedobjectmodel:objmodel];
    nsstring *dir = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes).firstobject;
    nsstring *path = [dir stringbyappendingstring:@"coredatademo.db"];
    nsurl *storeurl = [nsurl fileurlwithpath:path];
    nserror *error = nil;
    [persistentcoordinator addpersistentstorewithtype:nssqlitestoretype configuration:nil url:storeurl options:nil error:&error];
    if (!error) {
        nslog(@"数据库打开成功");
    } else {
        nslog(@"数据库打开失败:%@", [error description]);
    }
}

- (void)createobjcontext {
    if (objcontext != nil) {
        return;
    }
    nspersistentstorecoordinator *coordinator = persistentcoordinator;
    if (coordinator == nil) {
        return;
    }
    objcontext = [[nsmanagedobjectcontext alloc] initwithconcurrencytype:nsmainqueueconcurrencytype];
    objcontext.persistentstorecoordinator = coordinator;
}

(2)增加数据

- (bool)addscore:(nsdictionary *)dic {
    nsfetchrequest *request = [nsfetchrequest fetchrequestwithentityname:@"score"];
    request.predicate = [nspredicate predicatewithformat:@"identity=%@", dic[@"identity"]];
    nserror *error = nil;
    nsarray *results = [objcontext executefetchrequest:request error:&error];
    if (error == nil) {
        nslog(@"score查询成功");
    } else {
        nslog(@"score查询失败%@", [error description]);
        return no;
    }
    score *score = nil;
    if (results && results.count > 0) {
        score = results.firstobject;
    } else {
        score = [nsentitydescription insertnewobjectforentityforname:@"score" inmanagedobjectcontext:objcontext];
    }
    score.name = dic[@"name"];
    score.identity = dic[@"identity"];
    score.score = dic[@"score"];
    [objcontext save:&error];
    if (error == nil) {
        nslog(@"score 插入成功");
        return yes;
    } else {
        nslog(@"score插入失败%@", [error description]);
        return no;
    }
}

(3)删除数据

- (bool)deletescore:(nsstring *)identity {
    nsfetchrequest *request = [nsfetchrequest fetchrequestwithentityname:@"score"];
    request.predicate = [nspredicate predicatewithformat:@"identity=%@", identity];
    nserror *error = nil;
    nsarray *results = [objcontext executefetchrequest:request error:&error];
    score *score = nil;
    if (error == nil) {
        nslog(@"查询score成功");
    } else {
        nslog(@"查询score失败%@", [error description]);
        return no;
    }
    if (results && results.count) {
        score = results.firstobject;
    } else {
        nslog(@"数据中无符合条件的数据");
    }
    [objcontext deleteobject:score];
    [objcontext save:&error];
    if (error == nil) {
        nslog(@"score删除成功");
        return yes;
    } else {
        nslog(@"score删除失败%@", [error description]);
        return no;
    }
}

(4)修改数据

- (bool)updatescore:(nsdictionary *)dic {
    nsfetchrequest *request = [nsfetchrequest fetchrequestwithentityname:@"score"];
    request.predicate = [nspredicate predicatewithformat:@"identity=%@",dic[@"identity"]];
    nserror *error = nil;
    nsarray *results = [objcontext executefetchrequest:request error:&error];
    if (error == nil) {
        nslog(@"score查询成功");
    } else {
        nslog(@"score查询失败%@", [error description]);
        return no;
    }
    score *score = nil;
    if (results && results.count > 0) {
        score = results.firstobject;
    } else {
        score = [nsentitydescription insertnewobjectforentityforname:@"score" inmanagedobjectcontext:objcontext];
    }
    score.identity = dic[@"identity"];
    score.name = dic[@"name"];
    score.score = dic[@"score"];
    [objcontext save:&error];
    if (error == nil) {
        nslog(@"score更新成功");
        return yes;
    } else {
        nslog(@"score更新失败%@",[error description]);
        return no;
    }
}

(5)条件查询

- (nsarray *)getscore:(nsstring *)identity {
    nsfetchrequest *request = [nsfetchrequest fetchrequestwithentityname:@"score"];
    request.predicate = [nspredicate predicatewithformat:@"identity=%@", identity];
    nserror *error = nil;
    nsarray *results = [objcontext executefetchrequest:request error:&error];
    if (error == nil) {
        nslog(@"score查询成功");
    } else {
        nslog(@"score查询失败:%@", [error description]);
    }
    return results;
}

(6)获取全部数据

- (nsarray *)score {
    nsfetchrequest *request = [nsfetchrequest fetchrequestwithentityname:@"score"];
    nserror *error = nil;
    nsarray *results = [objcontext executefetchrequest:request error:&error];
    if (error == nil) {
        nslog(@"score查询成功");
    } else {
        nslog(@"score查询失败:%@",[error description]);
    }
    return results;
}