2010年11月30日火曜日

設定ファイルをplistで用意しておいて読み書きさせたい

Xcodeに追加したplistファイル。
これをアプリ側で読み書きさせたい。

こうやるっぽい。
・Document ディレクトリーにplistファイルをコピーして使う。

合ってるかわからないが、こうやってみた。
・plistファイルをコピーするDocument ディレクトリへのパスを取得する。
・そのパスにファイルがあるか確認する。
・ない。アプリを初めて起動するときは、ない。
・そのパスのファイルを作成する。(plistファイルをコピーして作成する。)
・以降は作成した(Document ディレクトリにある)ファイルを読み書きする。


  1. //  
  2. // かなーりコードを省略してます。当然ですがコピペしても動きませんよ。  
  3. //  
  4. @interface HogeAppDelegate : NSObject <uiapplicationdelegate, uitabbarcontrollerdelegate="">  
  5. {  
  6.  @private  
  7.  NSString *filepathToHogePlist_;  
  8. }  
  9.   
  10. @property (nonatomic, retain, readonly) NSString *filepathToHogePlist;  
  11.   
  12. - (NSString *)applicationDocumentsDirectory;  
  13.   
  14. @end  
  15. </uiapplicationdelegate,>  

  1. //  
  2. // かなーりコードを省略してます。当然ですがコピペしても動きませんよ。  
  3. //  
  4. @implementation HogeAppDelegate  
  5.   
  6. @synthesize filepathToHogePlist = filepathToHogePlist_;  
  7.   
  8. //  
  9. // [self applicationDocumentsDirectory] でDocument ディレクトリへのパスが取得できる  
  10. //  
  11. - (NSString *)applicationDocumentsDirectory  
  12. {  
  13.  return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];  
  14. }  
  15.   
  16. //  
  17. // アプリを初めて使うときに、plistをコピーしている。  
  18. //  
  19. // NSArray *hoges = [NSArray arrayWithContentsOfFile:self.filepathToHogePlist];  
  20. // とか    
  21. // [hogehogehoge writeToFile:self.filepathToHogePlist atomically:YES];  
  22. // みたいな感じで処理できるようになる。  
  23. //  
  24. - (NSString *)filepathToHogePlist  
  25. {  
  26.  if (filepathToHogePlist_!=nil) {  
  27.   return filepathToHogePlist_;  
  28.  }  
  29.    
  30.  BOOL success;  
  31.  NSFileManager* fileManager = [NSFileManager defaultManager];   
  32.  filepathToHogePlist_ = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"Hoge.plist"];  
  33.   
  34.  // アプリで用意したファイル(これをDocumentDirectoryにコピーして、以降はコピーしたファイルを読み書きさせる)  
  35.  success = [fileManager fileExistsAtPath:filepathToHogePlist_];  
  36.  if (!success)  
  37.  {  
  38.   NSBundle* bundle = [NSBundle mainBundle];  
  39.   NSString* bundlepath = [bundle pathForResource:@"Hoge" ofType:@"plist"];  
  40.   NSMutableArray *hoges = [NSMutableArray arrayWithContentsOfFile:bundlepath];  
  41.   [hoges writeToFile:filepathToHogePlist_ atomically:YES];   
  42.  }  
  43.    
  44.  return [filepathToHogePlist_ retain];  
  45. }  
  46.   
  47. @end  


こんな感じで。なんとなく。

で、iOSシミュレータの場合のDocumentDirectoryの場所
~/Library/Application Support/iPhone Simulator/バージョン/Applications/ランダムな文字列/Documents/Hoge.plist

0 件のコメント:

コメントを投稿