Objective-C:将值写入.plist中的Array的特定索引

时间:2012-10-09 10:04:04

标签: objective-c xcode nsarray nsdictionary writetofile

据我所知,我可以将一个值写入.plist文件

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"stored" ofType:@"plist"];
NSString *comment = @"this is a comment"; 
[comment writeToFile:filePath atomically:YES];

但是如果我想在我的.plist(gameArray)中说一个数组,我想将comment变成我的数组的特定索引,即gameArray[4];我该怎么做?

请允许我澄清

  • 我有一个plist:stored.plist
  • 在我的plist里面有一个数组gameArray
  • 我想更新plist中gameArray的特定索引 这可能吗 ?

2 个答案:

答案 0 :(得分:0)

假设' stored.plist'的内容是一个数组,您需要从路径实例化一个可变数组:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"stored" ofType:@"plist"];
NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:filePath];
NSString *comment = @"this is a comment"; 

// inserting a new object:
[array insertObject:comment atIndex:4];

// replacing an existing object:
// classic obj-c syntax
[array replaceObjectAtIndex:4 withObject:4];        
// obj-c literal syntax:
array[4] = comment;

// Cannot save to plist inside your document bundle.
// Save a copy inside ~/Library/Application Support

NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask] objectAtIndex:0];
NSURL *arrayURL = [documentsURL URLByAppendingPathComponent:[filePath lastPathComponent]];
[array writeToURL:arrayURL atomically:NO];

答案 1 :(得分:0)

您无法在应用程序的主程序包中更新和保存数据,而是必须在文档目录或其他目录中执行此操作:

 NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistFilePath = [documentsDirectory stringByAppendingPathComponent:@"stored.plist"];

if([[NSFileManager defaultManager] fileExistsAtPAth:plistFilePath]) 
{//already exits

   NSMutableArray *data = [NSMutableArray arrayWithContentsOfFile:plistFilePath];
   //update your array here
   NSString *comment = @"this is a comment";
   [data replaceObjectAtIndex:4 withObject:comment];

   //write file here
   [data writeToFile:plistFilePath atomically:YES];
}
else{ //firstly take content from plist and then write file document directory 

 NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"stored" ofType:@"plist"];
 NSMutableArray *data = [NSMutableArray arrayWithContentsOfFile:plistPath];
 //update your array here
   NSString *comment = @"this is a comment";
   [data replaceObjectAtIndex:4 withObject:comment];

   //write file here
   [data writeToFile:plistFilePath atomically:YES];
}