常见的数据保存方式有以下几种: 属性列表(plist) / 对象归档 / 内嵌数据库/ core data/ 设置束
1. 沙箱
概述:
iPhone的文件管理采用”沙箱”机制, 每次安装程序时,系统会为应用程序配置唯一的文件夹路径供其使用, 而其他程序则无法访问.
沙盒文件路径(Doccuments)包含了应用程序所有可以进行读写的文档.
Library :
<Applicatino_Home>/Library/Perferances/ 包含了用来设置用户偏好的文件,这里不能创建文件 只能通过NSUserDefult这个类来访问程序的偏好设置
<Application_Home>/Library/Cache
通常把特定路径的文件放到这个文件夹中, 程序作为缓存路径的持有者, 要负责文件的添加和删除工作, 这个路径下的文件在程序同步时不会被删除 .但是当系统内存不足时则会清理缓存
temp 包含需要的临时文件, 由用户管理, 程序退出时清空, 程序同步时, 不会备份
1.1沙盒相关文件路径的获取方法:
1.1.1 NSHomeDirectory 获取文件主路径
1.1.2 NSSeachPathForDirectoriesInDomanis 检索指定路径
NSString *documentPath = NSSeachPatthForDirectoriesInDomains(NSDocumnetsDirectory, NSUserDomainMask, YES) 获取documents 文件路径(三个参数:第一个参数指定了搜索的路径名称: NSDocumentDirectory 表示要查找的路径是 Documents; NSCacheDirectory 表示要查找的路径是 Cache; 第二个参数是一个常量, 即限制搜索范围为沙盒路径; 第三个参数 决定是否展开搜索到的文件路径)
1.1.3 NSTemporaryDirectory 获取临时文件夹全路径
1.2 NSFileManage(文件夹管理类)
1.2.2 常用操作: 创建/删除/复制/移动
创建文件夹
- (BOOL)- creatFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSSDictionary *)attr (三个参数: 第一个参数 为文件路径; 第二个参数为文件内容; 第三个参数为文件属性; 返回值表示是否创建成功
|
删除文件
—(BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error
|
移动及复制文件
- (BOOL) moveItemAtPath:(NSString*)srcPath toPath:(NSString *)dstPath error:(NSError **)
|
复制文件
- (BOOL) copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)
|
2 数据保存
2.1 属性列表 plist
iOS 中数组 字典 等基本类型可以通过 writeToFile: atoumically :方法将数据存储为plist类型 (第一个参数为文件存储路径, 第二个参数为是否使用辅助文件)
2.2 对象归档 archiving
归档应用与复杂对象类型的数据存储
归档 NSKeyedArchiver
反归档 NSKeyedUnarchiver
使用归档和反归档需要当前类支持NSCoding协议 , 同时对象的所有属性必须满足(属性为基本数据类型, 或者属性为实现NSCoding协议类的实例)
2.2.1 协议方法
- (void) encodeWithCoder:(NSCoder *)encoder
- (id)initWithCoder:(NSCoder *)decoder
|
2.2.2 复杂对象的归档/反归档步骤实例
归档
1) 创建可变数据类对象 NSMutableData *mData=[[ [NSMutableDta alloc] init] autorelease];
2) 创建归档对象 NSKeyedArchiver *arch= [[[NSKeyedArchiver alloc] initForWritingWithMutableData:mData];
3) 归档数据 [arch encodObject: aStu forKey:@"archData"];
4) 结束归档 [arch FinfshEncoding];
5) 将归档后的数据写到文件中 BOOL success = [mData writeToFile:PathAtomically:YES];
|
反归档
1) 读取需要被反归档的数据类型 NSData *data n=[[ [NSData alloc] initWithContentOfFile:path] autorelease];
2) 创建反归档对象 NSKeyedUnarchive *unarch = [[[NSKeyedUnarchive alloc] initForReadingWithData:Data] autorelease];
3) 创建对象 接受数据 Student *aStu = [unarch decodeObjectForKey:@"archData"];
4) 结束反归档
|
2.3 内嵌数据库库 sqlite
2.3.1 特点:
* 支持事件,不需要配置,不需要安装,不需要管理员;
* 支持大部分SQL92;
* 完整的数据库保存在磁盘上面一个文件,同一个数据库文件可以在不同机器上面使用,最大支持数据库到2T
* 整个系统少于3万行代码,少于250KB的内存占用;
* 源代码开发,代码95%有较好的注释,简单易用的API;
2.3.2 使用步骤:
1> 引入 <sqlite3.h> 头文件
2> 打开数据库
3> 执行SQL命令
4> 关闭数据库
2.3.3 SQLite常用系列函数
指针
sqlute3 代表数据库对象
sqlite3_stmt 代表SQL的指针
|
核心api
sqlite3_open() 打开数据库函数
sqlite3_prepare() 编译sql语句
sqlite3_step() 执行编译好的sql语句
sqlite3_exec() 执行sql语句的快捷方法 多用于不返回值得操作(增加, 删除 , 修改)
sqlite3_column() 一系列函数的总称, 他们的共同作用就是从当前的接种按列号取出值
例:sqlite3_column_int(stmt, 0)
sqlite3_finalize() 在sqlite3_stmt使用完毕后 , sqlite3_finalize()来销毁 /相当于release
sqlite3_close() 数据库操作结束后将数据库关闭。 关闭之前需要销毁所有的sqlite3_stmt对象
sqkite3_bind_xxx() sqlite3_column_count() 统计列数
sqlite3_data_count() 返回当前记录的列数
sqlite3_get_table() 获取被查询的表的内容
sqlite3_errmsg() 错误信息返回
sqlite3_reset() 重新装载sqlite语句
sqlite3_free() 释放动态构造的sqlite语句
|
不太常用的API
sqlite3_column_table_name 获取表名
sqlite3_column_origin_name()获取源名(索引名)
sqlite3_table_column_metadata() 获取一列的详细信息(表名, 建表类型)
|
2.3.4 实例
#import
<Foundation/Foundation.h>
#import <sqlite3.h> //引入Sqlite3.h的头文件 //封装sqlite3的函数调用, 以oc方法调用的形式去操作数据库 @interface DatabaseHandle : NSObject + ( id )sharedHandle; //单例方法的声明 //执行SQL语句的方法, 返回值为执行成功或者失败. - ( BOOL )execuateSQLStatement:( NSString *)SQLString; //执行查询语句的方法, 返回值是查询的记录组成的数组 - ( NSArray *)execuateQuerySQLStatement:( NSString *)SQLString; //设置数据库的名称
- (void)setDatabaseName:(NSString *)databaseName;
@end
|
#import
"DatabaseHandle.h"
@interface DatabaseHandle () @property ( nonatomic , retain ) NSString *fileName; //数据库文件名称 - ( sqlite3 *)openDattabase; //根据数据库文件的存储路径来打开数据库, 返回被打开的数据库指针 - ( NSString *)databaseFilePathWithName:( NSString *)name; //根据数据库的名称来返回数据库文件在沙盒中的存储路径. - ( BOOL )closeDatabase:( sqlite3 *)database; //关闭数据库 @end @implementation DatabaseHandle //static sqlite3 *_database;//声明静态的数据库指针变量,用于访问被打开的数据库 - ( void )dealloc { [ _fileName release ]; [ super dealloc ]; } #pragma mark - DataBase Operation - //数据库文件路径 - ( NSString *)databaseFilePathWithName:( NSString *)name { NSString *docPath = [ NSSearchPathForDirectoriesInDomains ( NSDocumentDirectory , NSUserDomainMask , YES ) lastObject ]; //返回数据库文件在documents文件夹中的存储路径 return [docPath stringByAppendingPathComponent :name]; } //打开数据库 -( sqlite3 *)openDattabase { NSString *filePath = [ self databaseFilePathWithName : self . fileName ]; NSLog ( @"%@" ,filePath); //声明sqlite3类型的数据库指针变量 sqlite3 *database = NULL ; //打开数据库的函数,第一个参数是 c 语言字符串描述的文件路径, 第二个参数是 需要保存数据库指针的指针变量的地址, 返回值为BOOL, 用来描述是否打开成功 int result = sqlite3_open (filePath. UTF8String , &database); //filePath.UTF8String 将字符串对象转化为 c 类型字符 if (result == 0 ) { return database; } return NULL ; } //关闭数据库 - ( BOOL )closeDatabase:( sqlite3 *)database { if (!database) { return NO ; } //将给定指针database指向的数据库关闭, 并返回关闭结果. BOOL result = sqlite3_close (database); database = NULL ; return result; } #pragma mark - SQL Statement execuate - - ( BOOL )execuateSQLStatement:( NSString *)SQLString { //1 打开数据库 sqlite3 *database = [ self openDattabase ]; //2 执行 SQL 语句 int result = sqlite3_exec (database, SQLString. UTF8String , NULL , NULL , NULL ); //3 关闭数据库 [ self closeDatabase :database]; //因为sqlite3_exec的返回值为int 有多重值所以需要加判断 NSLog ( @"%d" ,result); return result == 0 ? YES : NO ; } #pragma mark - initlization method - - ( void )setDatabaseName:( NSString *)databaseName { //判断给定的数据库文件名 如果不包含 .sqlite 后缀, 则拼接该后缀名 if (![databaseName containsString : @".sqlite" ]) { databaseName = [databaseName stringByAppendingString : @".sqlite" ]; } self . fileName = databaseName; } - ( NSArray *)execuateQuerySQLStatement:( NSString *)SQLString { //1 打开数据库 sqlite3 *database = [ self openDattabase ]; //2 声明数据集指针变量 sqlite3_stmt *statement = NULL ; //3 检查SQL语句, 并将检查无误的SQL写入到数据集指针中 /int 类型转换 int result = sqlite3_prepare (database, SQLString. UTF8String , ( int )SQLString. length , &statement, NULL ); //4 用于保存所有查询得到的记录的数组 NSMutableArray *queryList = [ NSMutableArray array ]; if (result == SQLITE_OK ) { while ( sqlite3_step (statement) == SQLITE_ROW ) { //如果执行完 step 函数, statemnt 指针中就会保留一条完整的记录, 并返回 int columnCount = sqlite3_column_count (statement); NSMutableDictionary *dict = [ NSMutableDictionary dictionary ]; //用于封装一条记录的各个字段值 for ( int i = 0 ;i < columnCount; i ++) { const char *columnName = sqlite3_column_name (statement, i); //获取字段名称 NSString *key = [ NSString stringWithCString :columnName encoding : NSUTF8StringEncoding ]; // c 语言字符串转化为oc字符串 //获取当前字段的数据类型 int type = sqlite3_column_type (statement, i); switch (type) { case SQLITE_INTEGER : { const int value = sqlite3_column_int (statement, i); [dict setObject :[ NSNumber numberWithInt :value] forKey :key]; } break ; case SQLITE_TEXT : { const unsigned char *value = sqlite3_column_text (statement, i); NSString *valueObject = [ NSString stringWithCString :( const char *)value encoding : NSUTF8StringEncoding ]; [dict setObject :valueObject forKey :key]; } break ; } } [queryList addObject :dict]; } } //5 关闭数据库 [ self closeDatabase :database]; //6 释放数据集指针所占的内存 sqlite3_finalize (statement); return queryList; } // //单例方法 +( id )sharedHandle { //指针变量定义在静态区 只有在第一次执行时才会在静态去创建hendle 指针变量 之后的执行中将不在执行 static DatabaseHandle *handle = nil ; if (!handle) { //不可以加autorelease handle = [[ self alloc ] init ]; } return handle; }
@end
|
/**
creat table sql
*/
/**创建表的语句, primary key 的作用就是标识当前的字段为主健, 主键的作用是约束当前字段的值必须是唯一的, 同时通过主键可以快速检索到对应的记录 */
/** integer 整形, text 文本类型, char 字符类型, blob 二进制类型, (NSData, 主要用于保存图片数据 */
create table Stu_info (stu_id integer primary key, name text, age integer, address text)
/* insert value */
/*插入语句中的格式为,insert into values ,values左侧的括号为字段名, 右侧的括号为对应的字段值*/
insert into Stu_info (stu_id, name, age, address)
values (1001,'Architect',18,'xian gao xin district');
/** UPDATE value */
/* 更新指定记录的操作
如果需要指定多个条件时可以用 or 关键字连接, 表示或者, 如果条件需要同时成立, 可以使用 and 关键字, 类似与C语言中的逻辑运算符 && 和 || ;
*/
UPDATE Stu_info SET name = 'Lulu', age = 25 WHERE stu_id = 1001;
/*select value*/
/* 返回列表中所有的记录的所有字段值 */
select *from Stu_info where stu_id = 1001 ;
/* 模糊查询, 查询的关键字时 like 使用通配符 %
D%% 表示以 D 开头;
%%D 表示以 D 结尾;
%%D%% 表示包含 D ;
*/
select * from Stu_info where name like '%%r%%';
/* DELETE VALUES */
/* 通过指定条件删除对应记录 */
delete from Stu_info WHERE stu_id = 1001;
delete from Stu_info WHERE name like '%%e%%';
/* drop teble */
/* 根据表名删除对应的表 */
drop table Stu_info;
|
3. 第三方数据解析