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

详解iOS应用开发中Core Data数据存储的使用

程序员文章站 2023-11-25 11:16:46
1.如果想创建一个带有coredata的程序,要在项目初始化的时候勾选中   2.创建完成之后,会发现在appdelegate里多出了几个属性,和2个方法...

1.如果想创建一个带有coredata的程序,要在项目初始化的时候勾选中
详解iOS应用开发中Core Data数据存储的使用 
2.创建完成之后,会发现在appdelegate里多出了几个属性,和2个方法

复制代码 代码如下:

<span style="font-size:18px;"> 
 
@property (readonly, strong, nonatomic) nsmanagedobjectcontext *managedobjectcontext; 
@property (readonly, strong, nonatomic) nsmanagedobjectmodel *managedobjectmodel; 
@property (readonly, strong, nonatomic) nspersistentstorecoordinator *persistentstorecoordinator; 
 
- (void)savecontext; 
- (nsurl *)applicationdocumentsdirectory;</span> 

core data数据持久化是对sqlite的一个升级,它是ios集成的,在说core data之前,我们先说说在coredata中使用的几个类。

(1)nsmanagedobjectmodel(被管理的对象模型)

相当于实体,不过它包含 了实体间的关系

(2)nsmanagedobjectcontext(被管理的对象上下文)

操作实际内容

作用:插入数据  查询  更新  删除

(3)nspersistentstorecoordinator(持久化存储助理)

相当于数据库的连接器

(4)nsfetchrequest(获取数据的请求)

相当于查询语句

(5)nspredicate(相当于查询条件)

(6)nsentitydescription(实体结构)

(7)后缀名为.xcdatamodel的包

里面的.xcdatamodel文件,用数据模型编辑器编辑

编译后为.momd或.mom文件,这就是为什么文件中没有这个东西,而我们的程序中用到这个东西而不会报错的原因。


3.如果想创建一个实体对象的话,需要点击.xcdatamodel,add entity,添加想要的字段

详解iOS应用开发中Core Data数据存储的使用详解iOS应用开发中Core Data数据存储的使用

4.生成对象文件,command+n,然后选中coredata里的nsmanagerobjectsubclass进行关联,选中实体创建

详解iOS应用开发中Core Data数据存储的使用

5.添加数据

复制代码 代码如下:

person *newperson = [nsentitydescription insertnewobjectforentityforname:@"person" inmanagedobjectcontext:self.managedobjectcontext]; 
     
    if (newperson == nil){ 
        nslog(@"failed to create the new person."); 
        return no; 
    } 
     
    newperson.firstname = paramfirstname; 
    newperson.lastname = paramlastname; 
    newperson.age = [nsnumber numberwithunsignedinteger:paramage]; 
    nserror *savingerror = nil; 
     
    if ([self.managedobjectcontext save:&savingerror]){ 
        return yes; 
    } else { 
        nslog(@"failed to save the new person. error = %@", savingerror); 
    } 

nsentitydescription(实体结构)相当于表格结构

6.取出数据查询

复制代码 代码如下:

/* create the fetch request first */ 
    nsfetchrequest *fetchrequest = [[nsfetchrequest alloc] init]; 
    /* here is the entity whose contents we want to read */ 
    nsentitydescription *entity = 
    [nsentitydescription 
     entityforname:@"person" 
     inmanagedobjectcontext:self.managedobjectcontext]; 
    /* tell the request that we want to read the
     contents of the person entity */ 
    [fetchrequest setentity:entity]; 
    nserror *requesterror = nil; 
    /* and execute the fetch request on the context */ 
    nsarray *persons = 
    [self.managedobjectcontext executefetchrequest:fetchrequest 
                                             error:&requesterror]; 
    /* make sure we get the array */ 
    if ([persons count] > 0){ 
        /* go through the persons array one by one */ 
        nsuinteger counter = 1; 
        for (person *thisperson in persons){ 
            nslog(@"person %lu first name = %@", 
                  (unsigned long)counter,  
                  thisperson.firstname);  
            nslog(@"person %lu last name = %@",  
                  (unsigned long)counter,  
                  thisperson.lastname); 
            nslog(@"person %lu age = %ld", 
                  (unsigned long)counter, 
                  (unsigned long)[thisperson.age unsignedintegervalue]); 
            counter++; 
        } 
    } else { 
        nslog(@"could not find any person entities in the context.");  
    } 

7.删除数据

复制代码 代码如下:

/* create the fetch request first */ 
    nsfetchrequest *fetchrequest = [[nsfetchrequest alloc] init]; 
    /* here is the entity whose contents we want to read */ 
    nsentitydescription *entity = 
    [nsentitydescription 
     entityforname:@"person" 
     inmanagedobjectcontext:self.managedobjectcontext]; 
    /* tell the request that we want to read the
     contents of the person entity */ 
    [fetchrequest setentity:entity]; 
    nserror *requesterror = nil; 
    /* and execute the fetch request on the context */ 
    nsarray *persons = 
    [self.managedobjectcontext executefetchrequest:fetchrequest 
                                             error:&requesterror]; 
    if ([persons count] > 0){ 
        /* delete the last person in the array */ 
        person *lastperson = [persons lastobject]; 
        [self.managedobjectcontext deleteobject:lastperson]; 
        nserror *savingerror = nil; 
        if ([self.managedobjectcontext save:&savingerror]){ 
            nslog(@"successfully deleted the last person in the array."); 
        } else { 
            nslog(@"failed to delete the last person in the array."); 
        } 
    } else {  
        nslog(@"could not find any person entities in the context.");  
    }  

8.排序

复制代码 代码如下:

<pre code_snippet_id="243955" snippet_file_name="blog_20140319_5_4289257" name="code" class="objc">nssortdescriptor *agesort =  
[[nssortdescriptor alloc] initwithkey:@"age"  
ascending:yes];  
nssortdescriptor *firstnamesort =  
[[nssortdescriptor alloc] initwithkey:@"firstname"  
ascending:yes];  
nsarray *sortdescriptors = [[nsarray alloc] initwithobjects:  
agesort,  
firstnamesort, nil nil];  
fetchrequest.sortdescriptors = sortdescriptors; </pre><p></p> 
<pre></pre> 
<p></p> 
<p style="background-color:rgb(255,255,255); margin:10px auto; padding-top:0px; padding-bottom:0px; font-family:verdana,'ms song',arial,helvetica,sans-serif; line-height:19.09090805053711px"> 
<span style="background-color:rgb(255,255,255)"><span style="font-size:18px"><br> 
</span></span></p> 
<span style="background-color:rgb(255,255,255)">注意</span><span style="font-size:18px; background-color:rgb(255,255,255)">ascending:yes 属性决定排序顺序</span><span style="background-color:rgb(255,255,255)"><span style="font-size:18px"><br> 
<br> 
<br> 
</span></span><br>