我在textFieldDidEndEditing上插入文本字段数据,进入数组。
但是我不想要重复的。如果用户更改了文本字段数据,我希望它被替换为字典中的新的和更新的,键名为"product",值为"bagel"。
. h
@interface Bread_TableViewController : UITableViewController <UITextFieldDelegate>
{
NSMutableArray *productarray;
}
m
- (void)viewDidLoad {
[super viewDidLoad];
productarray = [NSMutableArray array];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
// Make sure to set the label to have a ta
NSString*textfieldclicked;
if (textField.tag == 1) {
textfieldclicked=@"Unit";
} else if (textField.tag ==2) {
textfieldclicked=@"Case";
}
id textFieldSuper = textField;
while (![textFieldSuper isKindOfClass:[UITableViewCell class]]) {
textFieldSuper = [textFieldSuper superview];
}
NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)textFieldSuper];
InventoryTableViewCell *cell = (InventoryTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:textField.text,textfieldclicked,cell.product.text,@"product",nil];
[productarray addObject:plainPart];
}
你可以尝试这样做:
//the KEY exist
if ([productarray valueForKeyPath:YOUR_KEY]) {
//test if value doesn't exist for this key
if (![[productarray valueForKeyPath:YOUR_KEY] containsObject:YOUR_VALUE]) {
NSDictionary *oldPart = [[productarray valueForKeyPath:YOUR_KEY] firstObject];
NSInteger index = [productArray indexOfObject:oldPart];
[productarray replaceObjectAtIndex:index withObject:plainPart];
}
}
您可以使用NSMutableOrderedSet
,它的工作原理类似于NSArray,但它保证了元素的唯一性。
您不必担心实现-hash
和-isEqual:
,因为您使用的NSString
和NSDictionary
已经定义了它们。