深入理解iPhone資料持久化(手把手教你iphone開發 - 基礎篇)

來源:互聯網
上載者:User

作者:孫東風 2009-11-11(請尊重作者勞動成果,轉載務必註明出處)

在所有的移動開發平台資料持久化都是很重要的部分:在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(@"myfiles 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] myfiles path is :/Users/sundfsun2009/Library/Application Support/iPhone Simulator/User/Applications/C93DC783-F137-4660-AE5A-08C3E11C774B/Documents/myFile.rtf
Terminating in response to SpringBoards 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] myfiles path is :/Users/sundfsun2009/Library/Application Support/iPhone Simulator/User/Applications/763E6772-E754-452F-8532-80C2CE4466B5/Documents/myFile.rtf
Terminating in response to SpringBoards 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(@"myfiles 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] myfiles path is :/Users/sundfsu

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.