2012-10-09 64 views
0

我明白我可以例如值寫入一個文件的.plist這樣的Objective-C:寫的.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具體指標這是可能的?

回答

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]; 
+0

是,但現在你剛剛有一個數據類型'與指數4'comment' array',這不會寫的.plist,我想寫入實際.plist –

+0

已添加示例代碼保存到〜/ Library/Application Support/stored.plist – mrwalker

+0

是的,但是這會向.plist中添加一個數組,它不會更新現有數據:是不是可以更新現有數據? –

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]; 
} 
+0

謝謝你,但是你的代碼正在做的是向我的plist中添加一個'data'數組,我已經有一個數組了,我正在嘗試更新。 。 。 。 –

+0

首先找到你的根結構說這樣的數組或字典:NSMutableArray * data = [NSMutableArray arrayWithContentsOfFile:plistPath];或者NSMutableDictionary * data = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath]; –

+0

你的結構將與數組字典 –

相關問題