2012-03-15 52 views
0

我想要做的是從基於.plist的數組中填充pickerView,該.plist可以從textField中添加。我有它的工作,但它只添加一個鍵,並在添加新鍵時替換它。例如,如果我添加「hello」,然後嘗試添加另一個,它會用別的替換hello。基於textField將新密鑰寫入.plist文件

- (IBAction)setContext:(id)sender { 

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 

NSString *path = [[NSBundle mainBundle] pathForResource:@"fullArray" ofType:@"plist"]; 
NSString *textFieldText = textField.text; 

NSMutableDictionary *rootDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path]; 
[rootDict setValue:textField.text forKey:textField.text]; 

NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"fullArray.plist"]; 
[rootDict writeToFile:writablePath atomically: YES]; 

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

NSString *plistPath = [documentsDirectory  stringByAppendingPathComponent:@"fullArray.plist"]; //3 

NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath]; 
NSArray *array = [dictionary allKeys]; 

arrayContext = [[NSMutableArray alloc] initWithArray:array]; 

[pickerView selectRow:0 inComponent:0 animated:YES]; 

[textField endEditing:YES]; 

[pickerView reloadAllComponents]; 

} 

我該如何解決這個問題?

回答

2

好吧,你正在創建每次你撿東西的選擇器時新的NSMutableDictionary,正確的做法是:

  1. 創建的NSMutableDictionary作爲屬性。
  2. 每次你選擇時,都可以使用[NSString stringWithFormat:]爲該鍵創建一個新的字符串。
  3. 使用[mutableDictionary setObject:forKey]在突變字典中使用新創建的密鑰設置新對象。
+0

這裏我回答一個類似的問題,用代碼http://stackoverflow.com/questions/9673140/create-plist-file-via-code/9673615#9673615 – LuisEspinoza 2012-03-15 19:06:28

+0

和,你有veredict? – LuisEspinoza 2012-03-15 21:35:00

+0

不,我想要做的是在頂部有一個textField,並帶有一個按鈕將textField.text添加到數組中並將其寫入.plist。 – user1222053 2012-03-16 16:13:40