2012-05-29 51 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