在所有的移动开发平台数据持久化都是很重要的部分:在j2me中是rms或保存在应用程序的目录中,在symbian中可以保存在相应的磁盘目录中和数据库中。symbian中因为权限认证的原因,在3rd上大多数只能访问应用程序的private目录或其它系统共享目录。在iphone中,apple博采众长,提供了多种数据持久化的方法,下面笔者会逐个进行详细的讲解。
iphone提供的数据持久化的方法,从数据保存的方式上讲可以分为三大部分:属性列表、对象归档、嵌入式数据库(sqlite3)、其他方法。
一、属性列表NSUserDefaults
NSUserDefaults类的使用和NSKeyedArchiver有很多类似之处,但是查看NSUserDefaults的定义可以看出,NSUserDefaults直接继承自NSObject而NSKeyedArchiver 继承自NSCoder。这意味着NSKeyedArchiver实际上是个归档持久化的类,也就可以使用NSCoder类的[encodeObject: (ID)objv forKey:(Nsstring *)key]方法来对数据进行持久化存储。
- (voID)applicationDIDFinishLaunching:(UIApplication *)application {
Nsstring *strOne = @"Persistent data1";
Nsstring *strTwo = @"Persistent data 2";
NSMutableArray *persistentArray = [[NSMutableArray alloc] init];
[persistentArray addobject:strOne];
[persistentArray addobject:strTwo];
//archive
NSUserDefaults *persistentDefaults = [NSUserDefaults standardUserDefaults];
[persistentDefaults setobject:persistentArray forKey:@"myDefault"];
Nsstring *descriptionDefault = [persistentDefaults description];
NSLog(@"NSUserDefaults description is :%@",descriptionDefault);
//unarchive
NSArray *UnpersistentArray =
[persistentDefaults objectForKey:@"myDefault"];
Nsstring *UnstrOne = [UnpersistentArray objectAtIndex:0];
Nsstring *UnstrTwo = [UnpersistentArray objectAtIndex:1];
NSLog(@"UnstrOne = %@,UnstrTwo = %@",UnstrTwo);
// OverrIDe point for customization after application launch
[window makeKeyAndVisible];
}
二、对象归档NSKeyedArchiver和NSKeyedUnarchiver
iPhone和symbian 3rd一样,会为每一个应用程序生成一个私有目录,这个目录位于
/Users/sundfsun2009/library/Application Support/iPhone Simulator/User/Applications下,并随即生成一个数字字母串作为目录名,在每一次应用程序启动时,这个字母数字串都是不同于上一次的,上一次的应用程序目录信息被转换成名为.DS_Store隐藏文件,这个目录的文件结构如下图:
通常使用documents目录进行数据持久化的保存,而这个documents目录可以通过NSSearchPathForDirectorIEsInDomains(NSdocumentDirectory,NSUserdomainMask,YES)得到,代码如下:
- (voID)applicationDIDFinishLaunching:(UIApplication *)application {
Nsstring *strOne = @"Persistent data1";
Nsstring *strTwo = @"Persistent data 2";
NSArray *persistentArray = [NSArray arrayWithObjects:strOne,strTwo,nil];
NSArray *pathArray = NSSearchPathForDirectorIEsInDomains(NSdocumentDirectory,NSAllDomainsMask,YES);
int pathLen = [pathArray count];
NSLog(@"path number is :%d",pathLen);
Nsstring *filePath;
for(int i = 0; i < pathLen; i++)
{
filePath = [pathArray objectAtIndex:i];
NSLog(@"%d path is :%@",i,filePath);
}
Nsstring *myfilename = [filePath stringByAppendingPathComponent:@"myfile.rtf"];
NSLog(@"myfile's path is :%@",myfilename);
// no files generated in correspond directory Now
[NSKeyedArchiver archiveRootObject:persistentArray tofile:myfilename];
// Now the myfile.rtf is generated
// OverrIDe point for customization after application launch
[window makeKeyAndVisible];
}
NSSearchPathForDirectorIEsInDomains()的第二个参数是个枚举值,在笔者的测试代码中,只有NSUserDomainMask和NSAllDomainsMask可以获取到目录数为1,其余的皆为0,打印出来的结果如下:
[Session started at 2009-11-10 21:30:08 +0800.]
2009-11-10 21:30:10.516 PersistentExample[763:207] path number is :1
2009-11-10 21:30:10.518 PersistentExample[763:207] 0 path is :/Users/sundfsun2009/library/Application Support/iPhone Simulator/User/Applications/C93DC783-F137-4660-AE5A-08C3E11C774B/documents
2009-11-10 21:30:10.521 PersistentExample[763:207] myfile's path is :/Users/sundfsun2009/library/Application Support/iPhone Simulator/User/Applications/C93DC783-F137-4660-AE5A-08C3E11C774B/documents/myfile.rtf
Terminating in response to SpringBoard's termination.
[Session started at 2009-11-10 21:32:27 +0800.]
2009-11-10 21:32:30.091 PersistentExample[803:207] path number is :1
2009-11-10 21:32:30.092 PersistentExample[803:207] 0 path is :/Users/sundfsun2009/library/Application Support/iPhone Simulator/User/Applications/763E6772-E754-452F-8532-80C2CE4466B5/documents
2009-11-10 21:32:30.100 PersistentExample[803:207] myfile's path is :/Users/sundfsun2009/library/Application Support/iPhone Simulator/User/Applications/763E6772-E754-452F-8532-80C2CE4466B5/documents/myfile.rtf
Terminating in response to SpringBoard's termination.
从打印的结果如下,每次应用程序启动时生成的数字字母串目录名字并不一样。在调用[NSKeyedArchiver archiveRootObject:persistentArray tofile:myfilename]方法前,文件myfile.rtf并每生成,只有在调用此方法后才产生相应的文件。
下面需要把数据从属性列表中读取出来,在上面的代码中,笔者使用NSArray保存数据。但在大多数应用程序中,数据的尺寸并不是固定的,这个时候就需要使用NSMutalbeArray动态的保存数据,代码优化如下:
- (voID)applicationDIDFinishLaunching:(UIApplication *)application {
Nsstring *myfilename;
// archive
{
Nsstring *strOne = @"Persistent data1";
Nsstring *strTwo = @"Persistent data 2";
NSMutableArray *persistentArray = [[NSMutableArray alloc] init];
[persistentArray addobject:strOne];
[persistentArray addobject:strTwo];
NSArray *pathArray = NSSearchPathForDirectorIEsInDomains(NSdocumentDirectory,YES);
int pathLen = [pathArray count];
NSLog(@"path number is :%d",pathLen);
Nsstring *filePath;
for(int i = 0; i < pathLen; i++)
{
filePath = [pathArray objectAtIndex:i];
NSLog(@"%d path is :%@",filePath);
}
myfilename = [filePath stringByAppendingPathComponent:@"myfile.rtf"];
NSLog(@"myfile's path is :%@",myfilename);
[NSKeyedArchiver archiveRootObject:persistentArray tofile:myfilename];
}
// unarchive
{
NSArray *unarchiveArray = [NSKeyedUnarchiver unarchiveObjectWithfile:myfilename];
Nsstring *UnstrOne = [unarchiveArray objectAtIndex:0];
Nsstring *UnstrTwo = [unarchiveArray objectAtIndex:1];
NSLog(@"UnstrOne = );
}
// Override point for customization after application launch
[window makeKeyAndVisible];
}
输出结果如下:
[Session started at 2009-11-10 22:41:57 +0800.]
2009-11-10 22:41:59.344 PersistentExample[1082:207] path number is :1
2009-11-10 22:41:59.346 PersistentExample[1082:207] 0 path is :/Users/sundfsun2009/Library/Application Support/iPhone Simulator/User/Applications/055CD17C-864E-4A83-ABF0-5F01EE85BD5A/Documents
2009-11-10 22:41:59.355 PersistentExample[1082:207] myfile's path is :/Users/sundfsun2009/Library/Application Support/iPhone Simulator/User/Applications/055CD17C-864E-4A83-ABF0-5F01EE85BD5A/Documents/myFile.rtf
2009-11-10 22:41:59.357 PersistentExample[1082:207] UnstrOne = Persistent data1,UnstrTwo = Persistent data 2
Terminating in response to SpringBoard's termination.
从上面的图中可以看到,目录中还有个tmp目录,读者也可以把数据保存在tmp目录中,获取这个目录使用NSTemporaryDirectory()方法。
三、嵌入式数据库(SQLite3)
嵌入式数据库持久化数据就是把数据保存在iphone的嵌入式数据库系统SQLite3中,本质上来说,数据库持久化 *** 作是基于文件持久化基础之上的。
要使用嵌入式数据库SQLite3,首先需要加载其动态库libsqlite3.dylib,这个文件位于/Xcode3.1.4/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.1.sdk/usr/lib目录下。在Framework文件夹上右击,选择“Adding->Existing Files...”,定位到上述目录并加载到文件夹。
首先在头文件中做如下修改:
#import <UIKit/UIKit.h>
#include "sqlite3.h"
#define kFileName @"mydb.sql"
@interface PersistentExampleAppDelegate : NSObject <UIApplicationDelegate> {
sqlite3 *database;
UIWindow *window;
}
@property (nonatomic,retain) IBOutlet UIWindow *window;
@end
- (void)applicationDidFinishLaunching:(UIApplication *)application {
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *paths = [[path objectAtIndex:0] stringByAppendingPathComponent:kFileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL findFile = [fileManager fileExistsAtPath:paths];
NSLog(@"Database file path = %@",paths);
// 如果找到了数据库文件
if(findfile)
{
NSLog(@"Database file have already existed.");
if(sqlite3_open([paths UTF8String],&database) != sqlITE_OK)//打开数据库失败
{
sqlite3_close(database);
NSAssert(0,@"Failed to open database");
}
}else
{
NSLog(@"Database file does not exsit!");
if(sqlite3_open([paths UTF8String],@"Failed to open database");
}
}
char *errorMsg;
//创建表
Nsstring *createsql = @"create table if not exists fIElds (row integer primary key,fIEld_data text);";
if(sqlite3_exec(database,[createsql UTF8String],NulL,&errorMsg)!=sqlITE_OK)
{
sqlite3_close(database);
NSAssert1(0,@"Error creating table: %s",errorMsg);
}
Nsstring *strOne = @"Persistent data1";
Nsstring *strTwo = @"Persistent data 2";
NSMutableArray *persistentArray = [[NSMutableArray alloc] init];
[persistentArray addobject:strOne];
[persistentArray addobject:strTwo];
for (int i = 0; i < [persistentArray count]; i++) {
Nsstring *upDatasql = [[Nsstring alloc] initWithFormat:@"insert or replace into
fIElds (row,fIEld_data) values (%d,'%@');",[persistentArray objectAtIndex:i]];
char* errorMsg;
if(sqlite3_exec(database,[upDatasql UTF8String],&errorMsg)
!= sqlITE_OK)
{
sqlite3_close(database);
NSAssert(0,@"Failed to open database");
}
}
//unarchive
Nsstring *query = @"select row,fIEld_data from fIElds order by row";//查找表中的数据
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(database,[query UTF8String],-1,&statement,nil)
== sqlITE_OK)
{
while(sqlite3_step(statement) == sqlITE_ROW)
{
int row = sqlite3_column_int(statement,0);
char *rowData = (char *)sqlite3_column_text(statement,1);
Nsstring *fIEldname = [[Nsstring alloc] initWithFormat:@"show%d",row];
Nsstring *fIEldValue = [[Nsstring alloc] initWithUTF8String:rowData];
NSLog(@"fIEldname is :%@,fIEldValue is :%@",fIEldname,fIEldValue);
[fIEldname release];
[fIEldValue release];
}
sqlite3_finalize(statement);
}
// OverrIDe point for customization after application launch
[window makeKeyAndVisible];
}
在上面的代码中,我们使用
NSfileManager *fileManager = [NSfileManager defaultManager];
BOol findfile = [fileManager fileExistsAtPath:paths];
来判断数据库文件是否已经存在,其实在大多数情况下是没有必要的,sqlite3_open()方法会自动帮我们判断数据库文件是否存在,如果不存在则创建心的数据库文件。
四、其它方法
除了上面的三种方法来保存持久化数据以外,我们还可以用写文件到磁盘的方式来保存持久化数据。
- (voID)applicationDIDFinishLaunching:(UIApplication *)application {
Nsstring *strOne = @"Persistent data1";
Nsstring *strTwo = @"Persistent data 2";
NSMutableArray *persistentArray = [[NSMutableArray alloc] init];
[persistentArray addobject:strOne];
[persistentArray addobject:strTwo];
NSArray *filePathArray = NSSearchPathForDirectorIEsInDomains(NSdocumentDirectory,YES);
Nsstring *filePath =
- [[filePathArray objectAtIndex:0] stringByAppendingPathComponent:@"mydatas.pList"];
[[NSArray arrayWithObjects:persistentArray,nil] writetofile:filePath atomically:NO];
//load
NSMutableArray *saveDataArray = [[NSMutableArray alloc] init];
if([[NSfileManager defaultManager] fileExistsAtPath:filePath])
saveDataArray = [NSMutableArray arrayWithContentsOffile:filePath];
else
saveDataArray = [NSMutableArray arrayWithContentsOffile:[[NSBundle
- mainBundle] pathForResource:@"Savedatas" ofType:@"pList"]];
-
NSArray *strArray = [saveDataArray objectAtIndex:0];
Nsstring *UnstrOne = [strArray objectAtIndex:0];
Nsstring *UnstrTwo = [strArray objectAtIndex:1];
// OverrIDe point for customization after application launch
[window makeKeyAndVisible];
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/dongfengsun/archive/2009/11/11/4799249.aspx
总结以上是内存溢出为你收集整理的数据持久化全部内容,希望文章能够帮你解决数据持久化所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)