2010年11月30日火曜日

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

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

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

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



//
// かなーりコードを省略してます。当然ですがコピペしても動きませんよ。
//
@interface HogeAppDelegate : NSObject
{
@private
NSString *filepathToHogePlist_;
}

@property (nonatomic, retain, readonly) NSString *filepathToHogePlist;

- (NSString *)applicationDocumentsDirectory;

@end


//
// かなーりコードを省略してます。当然ですがコピペしても動きませんよ。
//
@implementation HogeAppDelegate

@synthesize filepathToHogePlist = filepathToHogePlist_;

//
// [self applicationDocumentsDirectory] でDocument ディレクトリへのパスが取得できる
//
- (NSString *)applicationDocumentsDirectory
{
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

//
// アプリを初めて使うときに、plistをコピーしている。
//
// NSArray *hoges = [NSArray arrayWithContentsOfFile:self.filepathToHogePlist];
// とか
// [hogehogehoge writeToFile:self.filepathToHogePlist atomically:YES];
// みたいな感じで処理できるようになる。
//
- (NSString *)filepathToHogePlist
{
if (filepathToHogePlist_!=nil) {
return filepathToHogePlist_;
}

BOOL success;
NSFileManager* fileManager = [NSFileManager defaultManager];
filepathToHogePlist_ = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"Hoge.plist"];

// アプリで用意したファイル(これをDocumentDirectoryにコピーして、以降はコピーしたファイルを読み書きさせる)
success = [fileManager fileExistsAtPath:filepathToHogePlist_];
if (!success)
{
NSBundle* bundle = [NSBundle mainBundle];
NSString* bundlepath = [bundle pathForResource:@"Hoge" ofType:@"plist"];
NSMutableArray *hoges = [NSMutableArray arrayWithContentsOfFile:bundlepath];
[hoges writeToFile:filepathToHogePlist_ atomically:YES];
}

return [filepathToHogePlist_ retain];
}

@end



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

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

0 件のコメント:

コメントを投稿