2011-08-05 42 views
2

我正在開發一個應用程序,我已經創建了plist,並且我正在向它添加數據..但是發生的情況是,每次數據被覆蓋並且以前的數據丟失了。我的意思是假設我添加一個名爲rocky的名字,下次我添加岩石,岩石被岩石覆蓋時,但我想要的是我的plist應該包含rocky和rock等等......我將數據添加到plist中用戶進入....動態添加數據到plist並填充tableview單元

這裏是我下面的代碼..

-(IBAction) myplist:(id) sender//the data is saved in a plist by clicking on this button 
{ 
NSLog(@"mylist Clicked");  

NSMutableArray *array = [[NSMutableArray alloc] init]; 

[array addObject:searchLabel.text]; 

    // get paths from root direcory 

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 

// get documents path 

NSString *documentsPath = [paths objectAtIndex:0]; 

// get the path to our Data/plist file 

NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"]; 



// This writes the array to a plist file. If this file does not already exist, it creates a new one. 

    [array writeToFile:plistPath atomically: TRUE]; 
} 

回答

0

我認爲這將用於您的目的,對您的代碼進行輕微修改。

NSLog(@"mylist Clicked");  
NSMutableArray *array = [[NSMutableArray alloc] init]; 


// get paths from root direcory 

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 

// get documents path 

NSString *documentsPath = [paths objectAtIndex:0]; 

// get the path to our Data/plist file 

NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"]; 


//This copies objects of plist to array if there is one 
[array addObjectsFromArray:[NSArray arrayWithContentsOfFile:plistPath]]; 
[array addObject:searchLabel.text]; 
// This writes the array to a plist file. If this file does not already exist, it creates a new one. 

[array writeToFile:plistPath atomically: TRUE]; 
+0

謝謝你索尼它的工作..和它正是我想要的......但現在..一個更多的問題,它在模擬器上工作..但如何使它在設備上運行..請幫助我。 – Ranjit

+0

嗨索尼,我想問一件事,我應該如果我想在plist中只添加3個值,然後如果用戶添加更多,然後我會被覆蓋......如何做到這一點? – Ranjit

0

嘗試使用順序將數據存儲到plist中。

1,檢索的plist舊數據成的NSMutableDictionary/NSMutableArray的

2,添加新記錄到的NSMutableDictionary/NSMutableArray裏

3,寫入文件

+0

感謝Vanya..for你的回覆..你可以讓我改變我應該在我以前的代碼中做什麼,這樣我就會得到我想要的笏。因爲我是新手...... – Ranjit

+0

你有沒有試過索尼的解決方案?看起來很好。 – Vanya

+0

嗨vanya ...我try..sonys解決方案,它工作正常..在模擬器..我想知道我們應該做什麼變化,以便它可以在iPhone設備上運行也.. – Ranjit

0

你不能追加數據到Plist。由於您每次都在執行writeToFile,所以plist文件會被重寫。所以最初存儲的數據將不會存在其中。唯一的另一種實現願望的方式是從plist中檢索數據。然後添加你的新數據對象到數組中。使用新添加的數組再次將plist文件寫入磁盤。 希望這有助於。

+0

感謝booleanBoy你的答覆..如果你告訴我,我應該在我的上述代碼中做出什麼改變,會更好,因爲,我是新的ot it .. – Ranjit