2012-05-29 82 views
0

您好我有一個視圖控制器與IBAction添加一個字符串到Plist NSMutableArray。從基於索引的數組中刪除對象

然後這個Plist被讀入另一個viewController,它是一個tableView。來自Plist數組的這個字符串填充字符串「1」(不含引號)的自定義單元格中的textField。這基本上是一個籃子系統,在這種情況下,用戶在購物籃中添加產品時,將1個字符串添加到填充qty文本框的qty數組中。這些數量的文本字段被動態地添加到籃子視圖中,所以在很多場合我都會有很多行包含帶有字符串「1」的文本框。

現在我遇到的問題是,當按鈕添加產品​​到購物籃被按下時,我有另一個alertView按鈕從plist中刪除產品。問題是我添加字符串這樣

NSString *string = @"1"; 

    [enteredQty2 addObject:string]; 
    NSArray *paths4 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory4 = [paths4 objectAtIndex:0]; 
    NSString *path4 = [documentsDirectory4 stringByAppendingPathComponent:@"qty.plist"]; 
    [enteredQty2 writeToFile:path4 atomically:YES]; 

,並刪除這樣

NSString *string = @"1"; 

    [enteredQty2 removeObject:string]; 
    NSArray *paths4 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory4 = [paths4 objectAtIndex:0]; 
    NSString *path4 = [documentsDirectory4 stringByAppendingPathComponent:@"qty.plist"]; 
    [enteredQty2 writeToFile:path4 atomically:YES]; 

我的問題是,如果我有幾個項目加入到他們都初步具備了籃下的字符串數量字符串爲「1」。那麼當我刪除對象時,會從所有qtyTextFields中刪除「1」,而不僅僅是所選的產品。當然,QtyTextFields根據用戶想要的數量改變,所以從數組中刪除「1」,假設數量「12」將不起作用。

我不知道最好的辦法是什麼,我應該不知何故標記字符串「1」,當我添加它並使用選定的標記刪除項目。當然,這些標籤必須是動態和獨特的?

任何幫助非常感激

回答

0

你的陣列應該可能包含NSDictionary對象而不是NSString。也許像下面的東西?

NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys: 
              [NSNumber numberWithInt:1], @"quantity", 
              @"yourUniqueProductId", @"id", 
              @"My Cool Product", @"title", nil]; 

然後,你可以該項目添加到陣列中:

[enteredQty2 addObject:item]; 

要刪除一個項目,你可以遍歷數組:

for (NSDictionary *item in enteredQty2) { 
     if ([[item objectForKey:@"id"] isEqualToString:@"yourUniqueProductId"]) { 
       [enteredQty2 removeObject:item]; 
       break; 
     } 
} 
+0

感謝您的回覆,當我點擊它崩潰的應用程序日誌只是說[__NSCFDictionary的intValue]按鈕:無法識別的選擇發送到實例0xa170310' –

+0

該代碼絕對是隻是一個例子,並將需要調整您的具體目的。但是哪個按鈕給出錯誤?要添加項目還是刪除? –

+0

嗨@Josh它增加了碰撞的項目。如果我檢查plist它創建的字典和鍵但崩潰。謝謝你的幫助! –

0

嗯,你已經運行到NSString緩存非常短的相同字符串的問題,並且即使創建了兩次也會返回相同的對象。然後,當您調用removeObject時,它會查找同一對象的多個副本,以便將其全部刪除。

這應該爲你工作:

// Returns the lowest index whose corresponding array value is equal to a given object 
NSInteger index = [enteredQty2 indexOfObject:string]; 

// delete the object at index 
if (index != NSNotFound) { 
    [enteredQty2 removeObjectAtIndex:index]; 
} 
+0

這是否還算幸運? – lnafziger