午夜欧美_国产视频一区二区_91精品国产综合久久久久久丝袜_亚洲精品久久久久久动漫_成人午夜精品一区二区三区_亚洲伦理影院

深入理解iPhone數據持久化

來源:網絡

點擊:1332

A+ A-

所屬頻道:新聞中心

關鍵詞: iPhone,數據持久化,開發

      在所有的移動開發平臺數據持久化都是很重要的部分:在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 = %@”,UnstrOne,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, 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);

      }

      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 = %@,UnstrTwo = %@”,UnstrOne,UnstrTwo);

      }

      // 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], &database) != SQLITE_OK)//打開數據庫失敗

      {

      sqlite3_close(database);

      NSAssert(0,@“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,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,‘%@’);”,i,[persistentArray objectAtIndex:i]];

      char* errorMsg;

      if(sqlite3_exec(database,[upDataSQL UTF8String],NULL,NULL,&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, NSUserDomainMask, 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];

      }

    (審核編輯: 智匯小新)

    聲明:除特別說明之外,新聞內容及圖片均來自網絡及各大主流媒體。版權歸原作者所有。如認為內容侵權,請聯系我們刪除。

    主站蜘蛛池模板: 精品国产欧美一区二区三区成人 | 欧美3p在线观看一区二区三区 | 欧美一区二区三区视频在线观看 | 久久久久国产一级毛片高清版 | 日韩在线亚洲 | 韩国精品一区二区久久 | 国产伦精品一区二区三区在线观看 | 亚洲欧美精品伊人久久 | 国产网站精品 | 国产在线精品成人一区二区三区 | 香港经典a毛片免费观看…伊人色综合久久 | 日韩电影第一页 | a一区二区三区视频 | 欧美叉叉 | 妖精视频一区二区三区 | 欧美二区三区 | 激情欧美一区二区三区 | 欧美高清在线精品一区二区不卡 | 日韩在线欧美高清一区 | 国产午夜高清一区二区不卡 | 欧美精品专区免费观看 | 日韩欧美中文 | 在线播放五十路乱中文 | 欧美日韩亚洲一区二区三区 | 九九久久国产精品大片 | 欧美视频一区二区三区 | 欧美成a人片在线观看 | 中文字幕欧美在线观看 | 欧美一级久久久久久久大片 | 欧美不卡在线视频 | 中文国产成人精品久久一 | 黄色小视频免费在线观看 | 亚洲第一区视频在线观看 | 亚洲欧美日韩在线观看二区 | 91精品国产91热久久p | 欧美激情亚洲图片 | 国产欧美又粗又猛又爽老 | 国产精品亚洲精品观看不卡 | 日韩欧美一区二区三区不卡在线 | 国内精品免费视频 | 在线观看国产 |