1

私は iPhone アプリに取り組んでおり、objective-c を使用して既存の plist ファイルに新しいキーと値のペアを追加する必要があります。これは私がこれまでに試したことです:

NSString *myFile=[[NSBundle mainBundle] pathForResource:@"Favourites" ofType:@"plist"];

dict = [[NSMutableDictionary alloc] initWithContentsOfFile:myFile];
[dict setObject:textContent forKey:keyName];
[dict writeToFile:myFile atomically:YES];

ただし、これを行うと、ファイルに書き込まれません。キーの値を変更するか、別のキーに追加することに基づいたリソースしか見たことがありません。これを達成する別の方法はありますか?

お時間をいただきありがとうございます

4

1 に答える 1

3

バンドルに変更を加えることはできません。.plistしたがって、ファイルをドキュメントディレクトリにコピーして、そこで操作を行う必要があります。

これらの行に沿ったもの:

//check for plist
//Get documents directory's location
NSArray*docDir=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString*filePath=[docDir objectAtIndex:0];
NSString*plistPath=[filePath stringByAppendingPathComponent:@"Favourites.plist"];

//Check plist's existance using FileManager
NSError*err=nil;
NSFileManager*fManager=[NSFileManager defaultManager];

if(![fManager fileExistsAtPath:plistPath])
{
    //file doesn't exist, copy file from bundle to documents directory

    NSString*bundlePath=[[NSBundle mainBundle] pathForResource:@"Favourites" ofType:@"plist"];
    [fManager copyItemAtPath:bundlePath toPath:plistPath error:&err];
}

//Get the dictionary from the plist's path
NSMutableDictionary*plistDict=[[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
 //Manipulate the dictionary
 [plistDict setObject:textContent forKey:keyName];
 //Again save in doc directory.
 [plistDict writeToFile:myFile atomically:YES];
于 2012-08-29T04:34:11.473 に答える