首页 > 代码库 > 14.ios之数据存取
14.ios之数据存取
iOS应用数据存储的常用方式
应用沙盒
模拟器应用沙盒的根路径在:(apple是用户名,6.0是模拟器版本)
/Users/apple/Library/Application Support/iPhoneSimulator/6.0/Applications
应用沙盒结构分析
应用沙盒目录的常见获取方式
NSString *home =NSHomeDirectory();
NSString*documents = [homestringByAppendingPathComponent:@"Documents"];
//不建议采用,因为新版本的操作系统可能会修改目录名
// NSUserDomainMask代表从用户文件夹下找
// YES代表展开路径中的波浪字符“~”
NSArray*array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, NO);
//在iOS中,只有一个目录跟传入的参数匹配,所以这个集合里面只有一个元素
NSString*documents = [arrayobjectAtIndex:0];
应用沙盒目录的常见获取方式
属性列表
属性列表-归档NSDictionary
//将数据封装成字典
NSMutableDictionary *dict =[NSMutableDictionary dictionary];
[dict setObject:@"母鸡" forKey:@"name"];
[dictsetObject:@"15013141314" forKey:@"phone"];
[dict setObject:@"27"forKey:@"age"];
//将字典持久化到Documents/stu.plist文件中
[dictwriteToFile:path atomically:YES];
属性列表-归档NSDictionary
属性列表-恢复NSDictionary
//读取Documents/stu.plist的内容,实例化NSDictionary
NSDictionary*dict = [NSDictionarydictionaryWithContentsOfFile:path];
NSLog(@"name:%@", [dictobjectForKey:@"name"]);
NSLog(@"phone:%@", [dictobjectForKey:@"phone"]);
NSLog(@"age:%@", [dictobjectForKey:@"age"]);
属性列表-NSDictionary的存储和读取过程
偏好设置
NSUserDefaults *defaults = [NSUserDefaultsstandardUserDefaults];
[defaultssetObject:@"itcast"forKey:@"username"];
[defaultssetFloat:18.0fforKey:@"text_size"];
[defaultssetBool:YESforKey:@"auto_login"];
偏好设置
NSUserDefaults*defaults = [NSUserDefaultsstandardUserDefaults];
NSString*username = [defaultsstringForKey:@"username"];
floattextSize = [defaultsfloatForKey:@"text_size"];
BOOLautoLogin = [defaultsboolForKey:@"auto_login"];
[defaults synchornize];
NSKeyedArchiver
每次归档对象时,都会调用这个方法。一般在这个方法里面指定如何归档对象中的每个实例变量,可以使用encodeObject:forKey:方法归档实例变量
每次从文件中恢复(解码)对象时,都会调用这个方法。一般在这个方法里面指定如何解码文件中的数据为对象的实例变量,可以使用decodeObject:forKey方法解码实例变量
NSKeyedArchiver-归档NSArray
NSKeyedArchiver-归档Person对象(Person.h)
@interface Person : NSObject<NSCoding> @property (nonatomic, copy) NSString *name; @property (nonatomic, assign) int age; @property (nonatomic, assign) float height; @end
NSKeyedArchiver-归档Person对象(Person.m)
@implementation Person - (void)encodeWithCoder:(NSCoder *)encoder { [encoder encodeObject:self.name forKey:@"name"]; [encoder encodeInt:self.age forKey:@"age"]; [encoder encodeFloat:self.height forKey:@"height"]; } - (id)initWithCoder:(NSCoder *)decoder { self.name = [decoder decodeObjectForKey:@"name"]; self.age = [decoder decodeIntForKey:@"age"]; self.height = [decoder decodeFloatForKey:@"height"]; return self; } - (void)dealloc { [super dealloc]; [_name release]; } @end
NSKeyedArchiver-归档Person对象(编码和解码)
Person*person =[[[Personalloc] init] autorelease];
person.name= @"MJ";
person.age= 27;
person.height= 1.83f;
[NSKeyedArchiverarchiveRootObject:persontoFile:path];
Person *person =[NSKeyedUnarchiverunarchiveObjectWithFile:path];
NSKeyedArchiver-归档对象的注意
[superencodeWithCode:encode];
确保继承的实例变量也能被编码,即也能被归档
self= [super initWithCoder:decoder];
确保继承的实例变量也能被解码,即也能被恢复
NSData
NSData-归档2个Person对象到同一文件中
归档(编码) // 新建一块可变数据区 NSMutableData *data = [NSMutableData data]; // 将数据区连接到一个NSKeyedArchiver对象 NSKeyedArchiver *archiver = [[[NSKeyedArchiver alloc] initForWritingWithMutableData:data] autorelease]; // 开始存档对象,存档的数据都会存储到NSMutableData中 [archiver encodeObject:person1 forKey:@"person1"]; [archiver encodeObject:person2 forKey:@"person2"]; // 存档完毕(一定要调用这个方法) [archiver finishEncoding]; // 将存档的数据写入文件 [data writeToFile:path atomically:YES];
NSData-从同一文件中恢复2个Person对象
恢复(解码) // 从文件中读取数据 NSData *data = [NSData dataWithContentsOfFile:path]; // 根据数据,解析成一个NSKeyedUnarchiver对象 NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; Person *person1 = [unarchiver decodeObjectForKey:@"person1"]; Person *person2 = [unarchiver decodeObjectForKey:@"person2"]; // 恢复完毕 [unarchiver finishDecoding];
利用归档实现深复制
比如对一个Person对象进行深复制 // 临时存储person1的数据 NSData *data = [NSKeyedArchiver archivedDataWithRootObject:person1]; // 解析data,生成一个新的Person对象 Student *person2 = [NSKeyedUnarchiver unarchiveObjectWithData:data]; // 分别打印内存地址 NSLog(@"person1:0x%x", person1); // person1:0x7177a60 NSLog(@"person2:0x%x", person2); // person2:0x7177cf0
SQLite3
create table t_person(name, age);
为了保证可读性,建议还是把字段类型加上:
create table t_person(name text, age integer);
创建、打开、关闭数据库
//path为:~/Documents/person.db
sqlite3*db;
intresult =sqlite3_open([path UTF8String], &db);
执行不返回数据的SQL语句
char*errorMsg; //用来存储错误信息
char*sql = "create table if notexists t_person(id integer primary key autoincrement, nametext, age integer);";
intresult =sqlite3_exec(db, sql, NULL, NULL, &errorMsg);
带占位符插入数据
char *sql = "insert into t_person(name, age) values(?, ?);"; sqlite3_stmt *stmt; if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) { sqlite3_bind_text(stmt, 1, "母鸡", -1, NULL); sqlite3_bind_int(stmt, 2, 27); } if (sqlite3_step(stmt) != SQLITE_DONE) { NSLog(@"插入数据错误"); } sqlite3_finalize(stmt); 代码解析: sqlite3_prepare_v2()返回值等于SQLITE_OK,说明SQL语句已经准备成功,没有语法问题
带占位符插入数据
查询数据
char *sql = "select id,name,age from t_person;"; sqlite3_stmt *stmt; if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) { while (sqlite3_step(stmt) == SQLITE_ROW) { int _id = sqlite3_column_int(stmt, 0); char *_name = (char *)sqlite3_column_text(stmt, 1); NSString *name = [NSString stringWithUTF8String:_name]; int _age = sqlite3_column_int(stmt, 2); NSLog(@"id=%i, name=%@, age=%i", _id, name, _age); } } sqlite3_finalize(stmt); 代码解析 sqlite3_step()返回SQLITE_ROW代表遍历到一条新记录 sqlite3_column_*()用于获取每个字段对应的值,第2个参数是字段的索引,从0开始
CoreData
模型文件
模型文件
模型文件
模型文件
NSManagedObject
CoreData主要对象
搭建Core Data上下文环境
NSManagedObjectModel*model = [NSManagedObjectModelmergedModelFromBundles:nil];
NSPersistentStoreCoordinator*psc =[[[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:model] autorelease];
NSString *docs =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) lastObject];
NSURL*url = [NSURLfileURLWithPath:[docsstringByAppendingPathComponent:@"person.data"]];
搭建Core Data上下文环境
添加持久化存储库,这里使用SQLite作为存储库 NSError *error = nil; NSPersistentStore *store = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error]; if (store == nil) { // 直接抛异常 [NSException raise:@"添加数据库错误" format:@"%@", [error localizedDescription]]; } 初始化上下文,设置persistentStoreCoordinator属性 NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; context.persistentStoreCoordinator = psc; // 用完之后,还是要[context release];
添加数据
传入上下文,创建一个Person实体对象 NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context]; 设置简单属性 [person setValue:@"MJ" forKey:@"name"]; [person setValue:[NSNumber numberWithInt:27] forKey:@"age"]; 传入上下文,创建一个Card实体对象 NSManagedObject *card = [NSEntityDescription insertNewObjectForEntityForName:@"Card" inManagedObjectContext:context]; [card setValue:@"4414241933432" forKey:@"no"]; 设置Person和Card之间的关联关系 [person setValue:card forKey:@"card"];
添加数据
利用上下文对象,将数据同步到持久化存储库 NSError *error = nil; BOOL success = [context save:&error]; if (!success) { [NSException raise:@"访问数据库错误" format:@"%@", [error localizedDescription]]; } // 如果是想做更新操作:只要在更改了实体对象的属性后调用[context save:&error],就能将更改的数据同步到数据库
查询数据
初始化一个查询请求 NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; 设置要查询的实体 NSEntityDescription *desc = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context]; 设置排序(按照age降序) NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO]; request.sortDescriptors = [NSArray arrayWithObject:sort]; 设置条件过滤(name like '%Itcast-1%') NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", @"*Itcast-1*"]; request.predicate = predicate;
执行请求 NSError *error = nil; NSArray *objs = [context executeFetchRequest:request error:&error]; if (error) { [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]]; } 遍历数据 for (NSManagedObject *obj in objs) { NSLog(@"name=%@", [obj valueForKey:@"name"] }
删除数据
传入需要删除的实体对象 [context deleteObject:managedObject]; 将结果同步到数据库 NSError *error = nil; [context save:&error]; if (error) { [NSException raise:@"删除错误" format:@"%@", [error localizedDescription]]; }
打开Core Data的SQL日志输出开关
CoreData的延迟加载
创建NSManagedObject的子类
创建NSManagedObject的子类
创建NSManagedObject的子类
14.ios之数据存取