iOS数据持久化的方式

摘要:
在iOS开发中,有很多数据持久化的方案,接下来我将尝试着介绍一下5种方案:plist文件preferenceNSKeyedArchiver(归档)SQLite3CoreData沙盒在介绍各种存储方法之前,有必要说明以下沙盒机制。iOS程序默认情况下只能访问程序自己的目录,这个目录被称为“沙盒”。NSString*path=NSTemporaryDirectory();NSLog;plist文件plist文件是将某些特定的类,通过XML文件的方式保存在目录中。NSKeyedArchiver归档在iOS中是另一种形式的序列化,只要遵循了NSCoding协议的对象都可以通过它实现序列化。

概论

所谓的持久化,就是将数据保存到硬盘中,使得在应用程序或机器重启后可以继续访问之前保存的数据。在iOS开发中,有很多数据持久化的方案,接下来我将尝试着介绍一下5种方案:

  • plist文件(属性列表)

  • preference(偏好设置)

  • NSKeyedArchiver(归档)

  • SQLite 3

  • CoreData

沙盒

在介绍各种存储方法之前,有必要说明以下沙盒机制。iOS程序默认情况下只能访问程序自己的目录,这个目录被称为“沙盒”。

1.结构

既然沙盒就是一个文件夹,那就看看里面有什么吧。沙盒的目录结构如下:

"应用程序包"
Documents
Library
Caches
Preferences
tmp

2.目录特性

虽然沙盒中有这么多文件夹,但是没有文件夹都不尽相同,都有各自的特性。所以在选择存放目录时,一定要认真选择适合的目录。

"应用程序包": 这里面存放的是应用程序的源文件,包括资源文件和可执行文件。

NSString*path=[[NSBundlemainBundle]bundlePath];
NSLog(@"%@",path);

Documents: 最常用的目录,iTunes同步该应用时会同步此文件夹中的内容,适合存储重要数据。

NSString*path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObject;
NSLog(@"%@",path);

Library/Caches: iTunes不会同步此文件夹,适合存储体积大,不需要备份的非重要数据。

NSString*path=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES).firstObject;
NSLog(@"%@",path);

Library/Preferences: iTunes同步该应用时会同步此文件夹中的内容,通常保存应用的设置信息。

tmp: iTunes不会同步此文件夹,系统可能在应用没运行时就删除该目录下的文件,所以此目录适合保存应用中的一些临时文件,用完就删除。

NSString*path=NSTemporaryDirectory();
NSLog(@"%@",path);

plist文件

plist文件是将某些特定的类,通过XML文件的方式保存在目录中。

可以被序列化的类型只有如下几种:

NSArray;
NSMutableArray;
NSDictionary;
NSMutableDictionary;
NSData;
NSMutableData;
NSString;
NSMutableString;
NSNumber;
NSDate;

1.获得文件路径

NSString*path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObject;
NSString*fileName=[pathstringByAppendingPathComponent:@"123.plist"];

2.存储

NSArray*array=@[@"123",@"456",@"789"];
[arraywriteToFile:fileNameatomically:YES];

3.读取

NSArray*result=[NSArrayarrayWithContentsOfFile:fileName];
NSLog(@"%@",result);

4.注意

  • 只有以上列出的类型才能使用plist文件存储。

  • 存储时使用writeToFile: atomically:方法。 其中atomically表示是否需要先写入一个辅助文件,再把辅助文件拷贝到目标文件地址。这是更安全的写入文件方法,一般都写YES。

  • 读取时使用arrayWithContentsOfFile:方法。

Preference

1.使用方法

//1.获得NSUserDefaults文件
NSUserDefaults*userDefaults=[NSUserDefaultsstandardUserDefaults];
//2.向文件中写入内容
[userDefaultssetObject:@"AAA"forKey:@"a"];
[userDefaultssetBool:YESforKey:@"sex"];
[userDefaultssetInteger:21forKey:@"age"];
//2.1立即同步
[userDefaultssynchronize];
//3.读取文件
NSString*name=[userDefaultsobjectForKey:@"a"];
BOOLsex=[userDefaultsboolForKey:@"sex"];
NSIntegerage=[userDefaultsintegerForKey:@"age"];
NSLog(@"%@,%d,%ld",name,sex,age);

2.注意

  • 偏好设置是专门用来保存应用程序的配置信息的,一般不要在偏好设置中保存其他数据。

  • 如果没有调用synchronize方法,系统会根据I/O情况不定时刻地保存到文件中。所以如果需要立即写入文件的就必须调用synchronize方法。

  • 偏好设置会将所有数据保存到同一个文件中。即preference目录下的一个以此应用包名来命名的plist文件。

NSKeyedArchiver

归档在iOS中是另一种形式的序列化,只要遵循了NSCoding协议的对象都可以通过它实现序列化。由于决大多数支持存储数据的Foundation和Cocoa Touch类都遵循了NSCoding协议,因此,对于大多数类来说,归档相对而言还是比较容易实现的。

1.遵循NSCoding协议

NSCoding协议声明了两个方法,这两个方法都是必须实现的。一个用来说明如何将对象编码到归档中,另一个说明如何进行解档来获取一个新对象。

  • 遵循协议和设置属性

//1.遵循NSCoding协议
@interfacePerson:NSObject//2.设置属性
@property(strong,nonatomic)UIImage*avatar;
@property(copy,nonatomic)NSString*name;
@property(assign,nonatomic)NSIntegerage;
@end
  • 实现协议方法

//解档
-(id)initWithCoder:(NSCoder*)aDecoder{
if([superinit]){
self.avatar=[aDecoderdecodeObjectForKey:@"avatar"];
self.name=[aDecoderdecodeObjectForKey:@"name"];
self.age=[aDecoderdecodeIntegerForKey:@"age"];
}
returnself;
}
//归档
-(void)encodeWithCoder:(NSCoder*)aCoder{
[aCoderencodeObject:self.avatarforKey:@"avatar"];
[aCoderencodeObject:self.nameforKey:@"name"];
[aCoderencodeInteger:self.ageforKey:@"age"];
}
  • 特别注意

如果需要归档的类是某个自定义类的子类时,就需要在归档和解档之前先实现父类的归档和解档方法。即 [super encodeWithCoder:aCoder] 和 [super initWithCoder:aDecoder] 方法;

2.使用

需要把对象归档是调用NSKeyedArchiver的工厂方法 archiveRootObject: toFile: 方法。

NSString*file=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObjectstringByAppendingPathComponent:@"person.data"];
Person*person=[[Personalloc]init];
person.avatar=self.avatarView.image;
person.name=self.nameField.text;
person.age=[self.ageField.textintegerValue];
[NSKeyedArchiverarchiveRootObject:persontoFile:file];

需要从文件中解档对象就调用NSKeyedUnarchiver的一个工厂方法 unarchiveObjectWithFile: 即可。

NSString*file=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObjectstringByAppendingPathComponent:@"person.data"];
Person*person=[NSKeyedUnarchiverunarchiveObjectWithFile:file];
if(person){
self.avatarView.image=person.avatar;
self.nameField.text=person.name;
self.ageField.text=[NSStringstringWithFormat:@"%ld",person.age];
}

3.注意

  • 必须遵循并实现NSCoding协议

  • 保存文件的扩展名可以任意指定

  • 继承时必须先调用父类的归档解档方法

SQLite3

之前的所有存储方法,都是覆盖存储。如果想要增加一条数据就必须把整个文件读出来,然后修改数据后再把整个内容覆盖写入文件。所以它们都不适合存储大量的内容。

1.字段类型

表面上SQLite将数据分为以下几种类型:

  • integer : 整数

  • real : 实数(浮点数)

  • text : 文本字符串

  • blob : 二进制数据,比如文件,图片之类的

实际上SQLite是无类型的。即不管你在创表时指定的字段类型是什么,存储是依然可以存储任意类型的数据。而且在创表时也可以不指定字段类型。SQLite之所以什么类型就是为了良好的编程规范和方便开发人员交流,所以平时在使用时最好设置正确的字段类型!主键必须设置成integer

2. 准备工作

准备工作就是导入依赖库啦,在iOS中要使用SQLite3,需要添加库文件:libsqlite3.dylib并导入主头文件,这是一个C语言的库,所以直接使用SQLite3还是比较麻烦的。

3.使用

  • 创建数据库并打开

操作数据库之前必须先指定数据库文件和要操作的表,所以使用SQLite3,首先要打开数据库文件,然后指定或创建一张表。

/**
*打开数据库并创建一个表
*/
-(void)openDatabase{
//1.设置文件名
NSString*filename=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObjectstringByAppendingPathComponent:@"person.db"];
//2.打开数据库文件,如果没有会自动创建一个文件
NSIntegerresult=sqlite3_open(filename.UTF8String,&_sqlite3);
if(result==SQLITE_OK){
NSLog(@"打开数据库成功!");
//3.创建一个数据库表
char*errmsg=NULL;
sqlite3_exec(_sqlite3,"CREATETABLEIFNOTEXISTSt_person(idintegerprimarykeyautoincrement,nametext,ageinteger)",NULL,NULL,&errmsg);
if(errmsg){
NSLog(@"错误:%s",errmsg);
}else{
NSLog(@"创表成功!");
}
}else{
NSLog(@"打开数据库失败!");
}
}
  • 执行指令

使用 sqlite3_exec() 方法可以执行任何SQL语句,比如创表、更新、插入和删除操作。但是一般不用它执行查询语句,因为它不会返回查询到的数据。

/**
*往表中插入1000条数据
*/
-(void)insertData{
NSString*nameStr;
NSIntegerage;
for(NSIntegeri=0;i<1000;i++){
nameStr=[NSStringstringWithFormat:@"Bourne-%d",arc4random_uniform(10000)];
age=arc4random_uniform(80)+20;
NSString*sql=[NSStringstringWithFormat:@"INSERTINTOt_person(name,age)VALUES('%@','%ld')",nameStr,age];
char*errmsg=NULL;
sqlite3_exec(_sqlite3,sql.UTF8String,NULL,NULL,&errmsg);
if(errmsg){
NSLog(@"错误:%s",errmsg);
}
}
NSLog(@"插入完毕!");
}
  • 查询指令

前面说过一般不使用 sqlite3_exec() 方法查询数据。因为查询数据必须要获得查询结果,所以查询相对比较麻烦。示例代码如下:

    • sqlite3_prepare_v2() : 检查sql的合法性

    • sqlite3_step() : 逐行获取查询结果,不断重复,直到最后一条记录

    • sqlite3_coloum_xxx() : 获取对应类型的内容,iCol对应的就是SQL语句中字段的顺序,从0开始。根据实际查询字段的属性,使用sqlite3_column_xxx取得对应的内容即可。

    • sqlite3_finalize() : 释放stmt

/**
*从表中读取数据到数组中
*/
-(void)readData{
NSMutableArray*mArray=[NSMutableArrayarrayWithCapacity:1000];
char*sql="selectname,agefromt_person;";
sqlite3_stmt*stmt;
NSIntegerresult=sqlite3_prepare_v2(_sqlite3,sql,-1,&stmt,NULL);
if(result==SQLITE_OK){
while(sqlite3_step(stmt)==SQLITE_ROW){
char*name=(char*)sqlite3_column_text(stmt,0);
NSIntegerage=sqlite3_column_int(stmt,1);
//创建对象
Person*person=[PersonpersonWithName:[NSStringstringWithUTF8String:name]Age:age];
[mArrayaddObject:person];
}
self.dataList=mArray;
}
sqlite3_finalize(stmt);
}

4.总结

总得来说,SQLite3的使用还是比较麻烦的,因为都是些c语言的函数,理解起来有些困难。不过在一般开发过程中,使用的都是第三方开源库 FMDB,封装了这些基本的c语言方法,使得我们在使用时更加容易理解,提高开发效率。

FMDB

1.简介

FMDB是iOS平台的SQLite数据库框架,它是以OC的方式封装了SQLite的C语言API,它相对于cocoa自带的C语言框架有如下的优点:

使用起来更加面向对象,省去了很多麻烦、冗余的C语言代码

对比苹果自带的Core Data框架,更加轻量级和灵活

提供了多线程安全的数据库操作方法,有效地防止数据混乱

注:FMDB的gitHub地址

2.核心类

FMDB有三个主要的类:

  • FMDatabase

一个FMDatabase对象就代表一个单独的SQLite数据库,用来执行SQL语句

  • FMResultSet

使用FMDatabase执行查询后的结果集

  • FMDatabaseQueue

用于在多线程中执行多个查询或更新,它是线程安全的

3.打开数据库

和c语言框架一样,FMDB通过指定SQLite数据库文件路径来创建FMDatabase对象,但FMDB更加容易理解,使用起来更容易,使用之前一样需要导入sqlite3.dylib。打开数据库方法如下:

NSString*path=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObjectstringByAppendingPathComponent:@"person.db"];
FMDatabase*database=[FMDatabasedatabaseWithPath:path];
if(![databaseopen]){
NSLog(@"数据库打开失败!");
}

值得注意的是,Path的值可以传入以下三种情况:

  • 具体文件路径,如果不存在会自动创建

  • 空字符串@"",会在临时目录创建一个空的数据库,当FMDatabase连接关闭时,数据库文件也被删除

  • nil,会创建一个内存中临时数据库,当FMDatabase连接关闭时,数据库会被销毁

4.更新

在FMDB中,除查询以外的所有操作,都称为“更新”, 如:create、drop、insert、update、delete等操作,使用executeUpdate:方法执行更新:

//常用方法有以下3种:
-(BOOL)executeUpdate:(NSString*)sql,...
-(BOOL)executeUpdateWithFormat:(NSString*)format,...
-(BOOL)executeUpdate:(NSString*)sqlwithArgumentsInArray:(NSArray*)arguments
//示例
[databaseexecuteUpdate:@"CREATETABLEIFNOTEXISTSt_person(idintegerprimarykeyautoincrement,nametext,ageinteger)"];
//或者
[databaseexecuteUpdate:@"INSERTINTOt_person(name,age)VALUES(?,?)",@"Bourne",[NSNumbernumberWithInt:42]];

5.查询

查询方法也有3种,使用起来相当简单:

-(FMResultSet*)executeQuery:(NSString*)sql,...
-(FMResultSet*)executeQueryWithFormat:(NSString*)format,...
-(FMResultSet*)executeQuery:(NSString*)sqlwithArgumentsInArray:(NSArray*)arguments

查询示例:

//1.执行查询
FMResultSet*result=[databaseexecuteQuery:@"SELECT*FROMt_person"];
//2.遍历结果集
while([resultnext]){
NSString*name=[resultstringForColumn:@"name"];
intage=[resultintForColumn:@"age"];
}

6.线程安全

在 多个线程中同时使用一个FMDatabase实例是不明智的。不要让多个线程分享同一个FMDatabase实例,它无法在多个线程中同时使用。 如果在多个线程中同时使用一个FMDatabase实例,会造成数据混乱等问题。所以,请使用 FMDatabaseQueue,它是线程安全的。以下是使用方法:

  • 创建队列。

FMDatabaseQueue*queue=[FMDatabaseQueuedatabaseQueueWithPath:aPath];
  • 使用队列

[queueinDatabase:^(FMDatabase*database){
[databaseexecuteUpdate:@"INSERTINTOt_person(name,age)VALUES(?,?)",@"Bourne_1",[NSNumbernumberWithInt:1]];
[databaseexecuteUpdate:@"INSERTINTOt_person(name,age)VALUES(?,?)",@"Bourne_2",[NSNumbernumberWithInt:2]];
[databaseexecuteUpdate:@"INSERTINTOt_person(name,age)VALUES(?,?)",@"Bourne_3",[NSNumbernumberWithInt:3]];
FMResultSet*result=[databaseexecuteQuery:@"select*fromt_person"];
while([resultnext]){
}
}];

而且可以轻松地把简单任务包装到事务里:

[queueinTransaction:^(FMDatabase*database,BOOL*rollback){
[databaseexecuteUpdate:@"INSERTINTOt_person(name,age)VALUES(?,?)",@"Bourne_1",[NSNumbernumberWithInt:1]];
[databaseexecuteUpdate:@"INSERTINTOt_person(name,age)VALUES(?,?)",@"Bourne_2",[NSNumbernumberWithInt:2]];
[databaseexecuteUpdate:@"INSERTINTOt_person(name,age)VALUES(?,?)",@"Bourne_3",[NSNumbernumberWithInt:3]];
FMResultSet*result=[databaseexecuteQuery:@"select*fromt_person"];
while([resultnext]){
}
//回滚
*rollback=YES;
}];

FMDatabaseQueue 后台会建立系列化的G-C-D队列,并执行你传给G-C-D队列的块。这意味着 你从多线程同时调用调用方法,GDC也会按它接收的块的顺序来执行。

.Core Data
Core Data本质上是使用SQLite保存数据,但是它不需要编写任何SQL语句。

要使用Core Data,需要在Xcode中的数据模型编辑器中设计好各个实体以及定义好他们的属性和关系。之后,通过操作这些对象,结合Core Data完成数据的持久化:

NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSError *error;
NSString *fieldName = [NSString stringWithFormat:@"test%d", i];
UITextField *theField = [self valueForKey:fieldName];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
//创 建描述语句,需求Line对象。类似于在数据库中限定为Line表。
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Line" inManagedObjectContext:context];
[request setEntity:entityDescription];
//创建限制性语句,类似于SQL语句中的 where lineNum = i
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(lineNum = %d)", i];
[request setPredicate:pred];
NSManagedObject *theLine = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil){
NSLog(@”There was an error!”);
// Do whatever error handling is appropriate
}
if ([objects count] > 0){ //如果符合条件的object存在,则取出
theLine = [objects objectAtIndex:0];
}
else { //如果不存在,则插入一个新的.
theLine = [NSEntityDescription insertNewObjectForEntityForName:@"Line"
inManagedObjectContext:context];
[theLine setValue:[NSNumber numberWithInt:i] forKey:@”lineNum”]; //设置这个object的属性,coredata会自动将其写入sqlite
[theLine setValue:theField.text forKey:@"lineText"];
[request release];

}

下面是其取数据的过程:

Core_Data_PersistenceAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Line"
inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil)
{
NSLog(@”There was an error!”);
// Do whatever error handling is appropriate
}
//每一个对象在CoreData中都表示为一个NSManagedObject对象(类似于数据库表中的每一行),他的属性通过键/值 方式获取
for (NSManagedObject *oneObject in objects)
{
NSNumber *lineNum = [oneObject valueForKey:@"lineNum"];
NSString *lineText = [oneObject valueForKey:@"lineText"];
}
[request release];

《转载 http://www.jianshu.com/p/6e048f7c5812》

文/伯恩的遗产(简书作者)
原文链接:http://www.jianshu.com/p/6e048f7c5812
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

一、CoreData的简单使用

准备工作

  • 创建数据库

    1. 新建文件,选择CoreData -> DataModel
    2. 添加实体(表),Add Entity
    3. 给表中添加属性,点击Attributes下方的‘+’
  • 创建模型文件

    1. 新建文件,选择CoreData -> NSManaged Object subclass
    2. 根据提示,选择实体
  • 通过代码,关联数据库和实体

    - (void)viewDidLoad {
       [super viewDidLoad];
    
       /*
        * 关联的时候,如果本地没有数据库文件,Coreadata自己会创建
        */
    
       // 1. 上下文
       NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
    
       // 2. 上下文关连数据库
    
       // 2.1 model模型文件
       NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
    
       // 2.2 持久化存储调度器
       // 持久化,把数据保存到一个文件,而不是内存
       NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    
       // 2.3 设置CoreData数据库的名字和路径
       NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
       NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
    
       [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
    
       context.persistentStoreCoordinator = store;
       _context = context;
    
    }

CoreData的基本操作(CURD)

  • 添加元素 - Create

    -(IBAction)addEmployee{
    
       // 创建一个员工对象 
       //Employee *emp = [[Employee alloc] init]; 不能用此方法创建
       Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
       emp.name = @"wangwu";
       emp.height = @1.80;
       emp.birthday = [NSDate date];
    
       // 直接保存数据库
       NSError *error = nil;
       [_context save:&error];
    
       if (error) {
           NSLog(@"%@",error);
       }
    }
  • 读取数据 - Read

      -(IBAction)readEmployee{
    
          // 1.FetchRequest 获取请求对象
          NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
    
          // 2.设置过滤条件
          // 查找zhangsan
          NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",
                              @"zhangsan"];
          request.predicate = pre;
    
          // 3.设置排序
          // 身高的升序排序
          NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
          request.sortDescriptors = @[heigtSort];
    
          // 4.执行请求
          NSError *error = nil;
    
          NSArray *emps = [_context executeFetchRequest:request error:&error];
          if (error) {
              NSLog(@"error");
          }
    
          //NSLog(@"%@",emps);
          //遍历员工
          for (Employee *emp in emps) {
              NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday);
          }
      }
  • 修改数据 - Update

    -(IBAction)updateEmployee{
       // 改变zhangsan的身高为2m
    
       // 1.查找到zhangsan
       // 1.1FectchRequest 抓取请求对象
       NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
    
       // 1.2设置过滤条件
       // 查找zhangsan
       NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@", @"zhangsan"];
       request.predicate = pre;
    
       // 1.3执行请求
       NSArray *emps = [_context executeFetchRequest:request error:nil];
    
       // 2.更新身高
       for (Employee *e in emps) {
           e.height = @2.0;
       }
    
       // 3.保存
       NSError *error = nil;
       [_context save:&error];
    
       if (error) {
           NSLog(@"%@",error);
       }
    }
  • 删除数据 - Delete

    -(IBAction)deleteEmployee{
    
       // 删除 lisi
    
       // 1.查找lisi
       // 1.1FectchRequest 抓取请求对象
       NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
    
       // 1.2设置过滤条件
       // 查找zhangsan
       NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",
                           @"lisi"];
       request.predicate = pre;
    
       // 1.3执行请求
       NSArray *emps = [_context executeFetchRequest:request error:nil];
    
       // 2.删除
       for (Employee *e in emps) {
           [_context deleteObject:e];
       }
    
       // 3.保存
       NSError *error = nil;
       [_context save:&error];
    
       if (error) {
           NSLog(@"%@",error);
       }
    
    }

二、CoreData的表关联

准备工作

  • 创建数据库

    1. 新建文件,选择CoreData -> DataModel
    2. 添加实体(表),Add Entity注意:这里根据关联添加多个实体
    3. 给表中添加属性,点击Attributes下方的‘+’
  • 创建模型文件

    1. 新建文件,选择CoreData -> NSManaged Object subclass
    2. 根据提示,选择实体,注意:这里先选择被关联的实体,最后添加最上层的实体
  • 通过代码,关联数据库和实体

    - (void)viewDidLoad {
       [super viewDidLoad];
    
       /*
        * 关联的时候,如果本地没有数据库文件,Coreadata自己会创建
        */
    
       // 1. 上下文
       NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
    
       // 2. 上下文关连数据库
    
       // 2.1 model模型文件
       NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
    
       // 2.2 持久化存储调度器
       // 持久化,把数据保存到一个文件,而不是内存
       NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    
       // 2.3 设置CoreData数据库的名字和路径
       NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
       NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
    
       [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
    
       context.persistentStoreCoordinator = store;
       _context = context;
    
    }

基本操作

  • 添加元素 - Create

    -(IBAction)addEmployee{
    
       // 1. 创建两个部门 ios android
       //1.1 iOS部门
       Department *iosDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context];
       iosDepart.name = @"ios";
       iosDepart.departNo = @"0001";
       iosDepart.createDate = [NSDate date];
    
       //1.2 Android部门
       Department *andrDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context];
       andrDepart.name = @"android";
       andrDepart.departNo = @"0002";
       andrDepart.createDate = [NSDate date];
    
       //2. 创建两个员工对象 zhangsan属于ios部门 lisi属于android部门
       //2.1 zhangsan
       Employee *zhangsan = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
       zhangsan.name = @"zhangsan";
       zhangsan.height = @(1.90);
       zhangsan.birthday = [NSDate date];
       zhangsan.depart = iosDepart;
    
       //2.2 lisi
       Employee *lisi = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
       lisi.name = @"lisi";
       lisi.height = @2.0;
       lisi.birthday = [NSDate date];
       lisi.depart = andrDepart;
    
       //3. 保存数据库
       NSError *error = nil;
       [_context save:&error];
    
       if (error) {
           NSLog(@"%@",error);
       }
    }
  • 读取信息 - Read

    -(IBAction)readEmployee{
    
       // 读取ios部门的员工
    
       // 1.FectchRequest 抓取请求对象
       NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
    
       // 2.设置过滤条件
       NSPredicate *pre = [NSPredicate predicateWithFormat:@"depart.name = %@",@"android"];
       request.predicate = pre;
    
         // 4.执行请求
       NSError *error = nil;
    
       NSArray *emps = [_context executeFetchRequest:request error:&error];
       if (error) {
           NSLog(@"error");
       }
    
       //遍历员工
       for (Employee *emp in emps) {
           NSLog(@"名字 %@ 部门 %@",emp.name,emp.depart.name);
       }
    }
  • 其他功能与前几种类似,这里不在赘述

三、CoreData的模糊查询

准备工作和上面类似,主要是查询方式不同

  • 模糊查询

    -(IBAction)readEmployee{
       // 1.FectchRequest 抓取请求对象
       NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
    
       // 2.设置排序
       // 按照身高的升序排序
       NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
       request.sortDescriptors = @[heigtSort];
    
       // 3.模糊查询
       // 3.1 名字以"wang"开头
    //    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"wangwu1"];
    //    request.predicate = pre;
    
       // 名字以"1"结尾
    //    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name ENDSWITH %@",@"1"];
    //    request.predicate = pre;
    
       // 名字包含"wu1"
    //    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"wu1"];
    //    request.predicate = pre;
    
       // like 匹配
       NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"*wu12"];
       request.predicate = pre;
    
       // 4.执行请求
       NSError *error = nil;
       NSArray *emps = [_context executeFetchRequest:request error:&error];
       if (error) {
           NSLog(@"error");
       }
    
       //遍历员工
       for (Employee *emp in emps) {
           NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday);
       }
    }
  • 分页查询

    -(void)pageSeacher{
       // 1. FectchRequest 抓取请求对象
       NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
    
       // 2. 设置排序
       // 身高的升序排序
       NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
       request.sortDescriptors = @[heigtSort];
    
       // 3. 分页查询
       // 总有共有15数据
       // 每次获取6条数据
       // 第一页 0,6
       // 第二页 6,6
       // 第三页 12,6 3条数据
    
       // 3.1 分页的起始索引
       request.fetchOffset = 12;
    
       // 3.2 分页的条数
       request.fetchLimit = 6;
    
       // 4. 执行请求
       NSError *error = nil;
       NSArray *emps = [_context executeFetchRequest:request error:&error];
       if (error) {
           NSLog(@"error");
       }
    
       // 5. 遍历员工
       for (Employee *emp in emps) {
           NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday);
       }
    }

四、多个数据库的使用

注意:

创建多个数据库,即创建多个DataModel
一个数据库对应一个上下文
需要根据bundle名创建上下文
添加或读取信息,需要根据不同的上下文,访问不同的实体

  • 关联数据库和实体

    - (void)viewDidLoad {
       [super viewDidLoad];
    
       // 一个数据库对应一个上下文
       _companyContext = [self setupContextWithModelName:@"Company"];
       _weiboContext = [self setupContextWithModelName:@"Weibo"];
    }        
    
    /**
    *  根据模型文件,返回一个上下文
    */
    -(NSManagedObjectContext *)setupContextWithModelName:(NSString *)modelName{
    
       // 1. 上下文
       NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
    
       // 2. 上下文关连数据库
       // 2.1 model模型文件
    
       // 注意:如果使用下面的方法,如果 bundles为nil 会把bundles里面的所有模型文件的表放在一个数据库
       //NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
    
       // 改为以下的方法获取:
       NSURL *companyURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"];
       NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:companyURL];
    
       // 2.2 持久化存储调度器
       // 持久化,把数据保存到一个文件,而不是内存
       NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    
       // 2.3 告诉Coredata数据库的名字和路径
       NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
       NSString *sqliteName = [NSString stringWithFormat:@"%@.sqlite",modelName];
       NSString *sqlitePath = [doc stringByAppendingPathComponent:sqliteName];
    
       [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
    
       context.persistentStoreCoordinator = store;
    
       // 3. 返回上下文
       return context;
    }
  • 添加元素

    -(IBAction)addEmployee{
       // 1. 添加员工
       Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_companyContext];
       emp.name = @"zhagsan";
       emp.height = @2.3;
       emp.birthday = [NSDate date];
    
       // 直接保存数据库
       [_companyContext save:nil];
    
       // 2. 发微博
       Status *status =[NSEntityDescription insertNewObjectForEntityForName:@"Status" inManagedObjectContext:_weiboContext];
    
       status.text = @"发了一条微博!";
       status.createDate = [NSDate date];
    
       [_weiboContext save:nil];
    }

免责声明:文章转载自《iOS数据持久化的方式》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇消息队列和管道的区别(转载)python编码encode decode(解惑)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

【山外笔记-Linux 命令】cp 命令详解

Linux 命令之 cp 命令详解 一、cp 命令简介 cp 命令主要用于复制文件或目录。即用来将一个或多个源文件或者目录复制到指定的目的文件或目录。 cp 命令可以将单个源文件复制成一个指定文件名的具体的文件或一个已经存在的目录下。 cp 命令支持同时复制多个文件,当一次复制多个文件时,目标文件参数必须是一个已经存在的目录,否则将出现错误。 二、cp...

Centos-对比文件差异-diff

diff   比较文件差异 相关选项   -c      显示全部内容,并标记不同之处   -b      忽略行尾空格,并认为字符串中一个或多个空格视为相同   -r       当比较双方都是目录时,会比较子目录中的文件   -s      当两个文件相同时,会显示文件的相同信息 相关信息    a    追加   d     删除   c     修...

V8 初次接触(Qt5) 1+1=2 博客频道 CSDN.NET

V8 初次接触(Qt5) - 1+1=2 - 博客频道 - CSDN.NET V8 初次接触(Qt5) 分类:QtQt52011-09-03 18:411881人阅读评论(4)收藏举报 在Qt5中,javascript 和 C++一样,成了Qt中的一等公民;而Qt选中的javascript引擎则是 V8。 看来,有必要简单看看这个东西了。 V8...

你必须知道的ADO.NET(八) 深入理解DataAdapter(上)

摘要 ADO.NET有两个核心组件:基于连接的Data Provider组件以及基于非连接的DataSet组件。基于连接的Data Provider组件常用于实时地从数据库中检索数据。而基于非连接的DataSet,似乎与数据库没有直接联系,仅仅用于在本地内存中存储Data Provider提供的数据表或集合。这一切似乎很微妙,此时,你是否在想:这两大组件...

django集成ansibe实现自动化

动态生成主机列表和相关参数 def create_admin_domain(admin_node): workpath = BASE_DIR + '/tools/ansible/script' hosts_file = BASE_DIR + '/tools/ansible/host/' + createhostfile() yml...

Linux下的压缩和解压缩命令gzip/gunzip

作者:邓聪聪 Linux下的压缩和解压缩命令——gzip/gunzip yum -y install zip gzip (--安装压缩工具) gzip命令 gzip命令用来压缩文件。gzip是个使用广泛的压缩程序,文件经它压缩过后,其名称后面会多处“.gz”扩展名。 gzip是在Linux系统中经常使用的一个对文件进行压缩和解压缩的命令,既方便又...