标签:
在iOS中,实现数据持久化一般分为4大种:
1、属性列表
2、对象归档
3、SQLite
4、Core Data
一、属性列表
NSUserDefaults类的使用和NSKeyedArchiver有很多类似之处,但是查看NSUserDefaults的定义可以看出,NSUserDefaults直接继承自NSObject而NSKeyedArchiver继承自NSCoder.这意味着NSKeyedArchiver实际上是个归档类持久化的类,也就是可以使用NSCoder类的[encodeObject:(id)obj forKey:(NSString *)key]方法来数据持久化。
1、创建NSUserDefaults对象
NSUserDefaults *mySettingData = [NSUserDefaults standardUserDefaults];
2、创建NSUserDefaults对象之后即可往里面添加数据,它支持的数据类型有NSString,NSNumber,NSDate、NSArray、NSDictionary、BOOL、NSInteger、NSFloat等系统定义的数据类型,如果要存放自定义的对象,则必须将其转换为NSData类型。
NSArray *arr = [[NSArray alloc] initWithObjects:@"arr1", @"arr2", nil] [mySettingData setObject:arr forKey:@"arrItem"]; [mySettingData setObject:@"admin" forKey:@"user_name"]; [mySettingData setBOOL:@YES forKey:@"auto_login"]; [mySettingData setInteger:1 forKey:@"count"];
3、往NSUserDefaults添加数据后,它们就变成了全局的变量,App中即可读写NSUserDefaults中的数据。
NSUserDefaults *mySettingDataR = [NSUserDefaults standardUserDefaults]; NSLog(@"arrItem=%@", [mySettingDataR objectForKey:@"arrItem"]); NSLog(@"user_name=%@", [mySettingDataR objectForKey:@"user_name"]); NSLog(@"count=%d", [mySettingDataR integerForKey:@"count"]);
4、如果想删除某个数据项,可以使用removeObjectForKey删除数据
[mySettingData removeObjectForKey:@"arrItem"];
5、需要注意的是,NSUserDefaults是定时把缓存中的数据写入磁盘的,而不是即时写入,为了防止在写完NSUserDefaults后程序退出导致的数据丢失,可以在写入数据后使用synchronize强制立即将数据写入磁盘:
[mySettingData synchronize];
运行上面得语句后,NSUserDefaults中的数据被写入到.plist文件中,如果是在模拟器上运行程序,可以在Mac的/Users/YOUR-USERNAME/Library/Application Support/iPhone Simulator/4.1/Applications/YOUR-APP-DIR/Library/Prefereces目录下找到一个文件名为YOUR-Bundle_Identifier.plist的plist文件,用Xcode打开该文件,可以看到刚才写入的数据。
二、对象归档
要使用对象归档,对象必须实现NSCoding协议,大部分OC对象都符合NSCoding协议,也可以在自定义对象中实现NSCoding协议,要实现NSCoding协议,需实现两个方法:
- (void) encodeWithCoder:(NSCoder *)encoder 与 -(void)initWithCoder:(NSCoder *)encoder
同时、建议对象也同时实现NSCopying协议,该协议允许复制对象,要实现NSCopying协议需实现 -(id)copyWithZone:(NSZone *)zone 方法
@interface User : NSObject <NSCoding>
@property (nonatomic, assign) NSInteger userID;
@property (nonatomic, copy) NSString *name;
?@end
@implementation User
// 以下两个方法一定要实现,不然在调用的时候会crash
- (void)encodeWithCoder:(NSCoder *)aCoder; 
{
// 这里放置需要持久化的属性
[aCoder encodeObject:[NSNumber numberWithInteger:self.userID] forKey:@”userID”];
[aCoder encodeObject:self.name forKey:@"name"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [self init])
{
//  这里务必和encodeWithCoder方法里面的内容一致,不然会读不到数据
self.userID = [[aDecoder decodeObjectForKey:@"userID"] integerValue];
self.name = [aDecoder decodeObjectForKey:@"name"];
}
return self;
}
// 使用方法
+ (BOOL)save {
NSError *error = nil;
// 确定存储路径,一般是Document目录下的文件
NSString* fileName = [self getFileName];
NSString* filePath = [self getFilePath];
if (![[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:&error]) {
NSLog(@”创建用户文件目录失败”);
return NO;
}
return [NSKeyedArchiver archiveRootObject:self toFile:[fileName:userId]];
}
?@end
三、SQLite
准备工作:导入相关库文件:libsqlit3.dylib。
使用:
1、创建数据库并打开:
/**
*  打开数据库并创建一个表
*/
- (void)openDatabase {
   //1.设置文件名
   NSString *filename = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.db"];
   //2.打开数据库文件,如果没有会自动创建一个文件
   NSInteger result = sqlite3_open(filename.UTF8String, &_sqlite3);
   if (result == SQLITE_OK) {
       NSLog(@"打开数据库成功!");
       //3.创建一个数据库表
       char *errmsg = NULL;
       sqlite3_exec(_sqlite3, "CREATE TABLE IF NOT EXISTS t_person(id integer primary key autoincrement, name text, age integer)", NULL, NULL, &errmsg);
       if (errmsg) {
           NSLog(@"错误:%s", errmsg);
       } else {
           NSLog(@"创表成功!");
       }
   } else {
       NSLog(@"打开数据库失败!");
   }
}
2、执行语句。使用sqlite3_exec()方法可以执行任何SQL语句,比如创建表、更新、插入、删除操作。
/**
*  往表中插入1000条数据
*/
- (void)insertData {
NSString *nameStr;
NSInteger age;
for (NSInteger i = 0; i < 1000; i++) {
  nameStr = [NSString stringWithFormat:@"Bourne-%d", arc4random_uniform(10000)];
  age = arc4random_uniform(80) + 20;
  NSString *sql = [NSString stringWithFormat:@"INSERT INTO t_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() 方法查询数据。因为查询数据必须要获得查询结果,所以查询相对比较麻烦。示例代码如下:
/**
*  从表中读取数据到数组中
*/
- (void)readData {
   NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:1000];
   char *sql = "select name, age from t_person;";
   sqlite3_stmt *stmt;
   NSInteger result = 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);
           NSInteger age = sqlite3_column_int(stmt, 1);
           //创建对象
           Person *person = [Person personWithName:[NSString stringWithUTF8String:name] Age:age];
           [mArray addObject:person];
       }
       self.dataList = mArray;
   }
   sqlite3_finalize(stmt);
}
总体来说,使用SQLite比较麻烦,因为里面都是一些C语言函数。在开发中,一般不使用SQLite,而是使用第三方开源库FMDB,DMDB封装了SQLite。
FMDB
1.简介
FMDB是iOS平台的SQLite数据库框架,它是以OC的方式封装了SQLite的C语言API,它相对于cocoa自带的C语言框架有如下的优点:
使用起来更加面向对象,省去了很多麻烦、冗余的C语言代码
对比苹果自带的Core Data框架,更加轻量级和灵活
提供了多线程安全的数据库操作方法,有效地防止数据混乱
2.核心类
FMDB有三个主要的类:
FMDatabase
一个FMDatabase对象就代表一个单独的SQLite数据库,用来执行SQL语句
FMResultSet
使用FMDatabase执行查询后的结果集
FMDatabaseQueue
用于在多线程中执行多个查询或更新,它是线程安全的
3.打开数据库
和c语言框架一样,FMDB通过指定SQLite数据库文件路径来创建FMDatabase对象,但FMDB更加容易理解,使用起来更容易,使用之前一样需要导入sqlite3.dylib。打开数据库方法如下:
| 
 1 
2 
3 
4 
5 
 | 
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.db"];FMDatabase *database = [FMDatabase databaseWithPath:path];    if (![database open]) {    NSLog(@"数据库打开失败!");} | 
值得注意的是,Path的值可以传入以下三种情况:
具体文件路径,如果不存在会自动创建
空字符串@"",会在临时目录创建一个空的数据库,当FMDatabase连接关闭时,数据库文件也被删除
nil,会创建一个内存中临时数据库,当FMDatabase连接关闭时,数据库会被销毁
4.更新
在FMDB中,除查询以外的所有操作,都称为“更新”, 如:create、drop、insert、update、delete等操作,使用executeUpdate:方法执行更新:
| 
 1 
2 
3 
4 
5 
6 
7 
8 
 | 
//常用方法有以下3种:   - (BOOL)executeUpdate:(NSString*)sql, ...- (BOOL)executeUpdateWithFormat:(NSString*)format, ...- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments//示例[database executeUpdate:@"CREATE TABLE IF NOT EXISTS t_person(id integer primary key autoincrement, name text, age integer)"];   //或者  [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES(?, ?)", @"Bourne", [NSNumber numberWithInt:42]]; | 
5.查询
查询方法也有3种,使用起来相当简单:
| 
 1 
2 
3 
 | 
- (FMResultSet *)executeQuery:(NSString*)sql, ...- (FMResultSet *)executeQueryWithFormat:(NSString*)format, ...- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments | 
查询示例:
| 
 1 
2 
3 
4 
5 
6 
7 
 | 
//1.执行查询FMResultSet *result = [database executeQuery:@"SELECT * FROM t_person"];//2.遍历结果集while ([result next]) {    NSString *name = [result stringForColumn:@"name"];    int age = [result intForColumn:@"age"];} | 
6.线程安全
在多个线程中同时使用一个FMDatabase实例是不明智的。不要让多个线程分享同一个FMDatabase实例,它无法在多个线程中同时使用。 如果在多个线程中同时使用一个FMDatabase实例,会造成数据混乱等问题。所以,请使用 FMDatabaseQueue,它是线程安全的。以下是使用方法:
创建队列。
| 
 1 
 | 
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath]; | 
使用队列
| 
 1 
2 
3 
4 
5 
6 
7 
8 
 | 
[queue inDatabase:^(FMDatabase *database) {              [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_1", [NSNumber numberWithInt:1]];              [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_2", [NSNumber numberWithInt:2]];              [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_3", [NSNumber numberWithInt:3]];                FMResultSet *result = [database executeQuery:@"select * from t_person"];             while([result next]) {            }    }]; | 
而且可以轻松地把简单任务包装到事务里:
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
 | 
[queue inTransaction:^(FMDatabase *database, BOOL *rollback) {              [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_1", [NSNumber numberWithInt:1]];              [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_2", [NSNumber numberWithInt:2]];              [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_3", [NSNumber numberWithInt:3]];                FMResultSet *result = [database executeQuery:@"select * from t_person"];                 while([result next]) {                }              //回滚           *rollback = YES;      }]; | 
CoreData
Core Data是iOS5之后才出现的一个框架,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数据库中的数据还原成OC对象。在此数据操作期间,我们不需要编写任何SQL语句,这个有点类似于著名的Hibernate持久化框架,不过功能肯定是没有Hibernate强大的。简单地用下图描述下它的作用:

左边是关系模型,即数据库,数据库里面有张person表,person表里面有id、name、age三个字段,而且有2条记录;
右边是对象模型,可以看到,有2个OC对象;
利用Core Data框架,我们就可以轻松地将数据库里面的2条记录转换成2个OC对象,也可以轻松地将2个OC对象保存到数据库中,变成2条表记录,而且不用写一条SQL语句。
创建数据库
CoreData -> DataModelAdd EntityAttributes下方的‘+’号创建模型文件
CoreData -> NSManaged Object subclass通过代码,关联数据库和实体
- (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{
   // 创建一个员工对象 
   //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 -> DataModelAdd Entity , 注意:这里根据关联添加多个实体Attributes下方的‘+’号创建模型文件
CoreData -> NSManaged Object subclass通过代码,关联数据库和实体
- (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);
   }
}
其他功能与前几种类似,这里不在赘述
准备工作和上面类似,主要是查询方式不同
模糊查询
-(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];
}
标签:
原文地址:http://www.cnblogs.com/shaoting/p/4858724.html