0

我知道我可以例如将值写入 .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];我该怎么做?

请允许我澄清一下

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

2 回答 2

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];
}
于 2012-10-09T10:19:06.273 回答
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];
于 2012-10-09T10:15:16.273 回答