我有添加和删除按钮,可在视图中添加文本字段。现在我想将文本字段值存储在字典中。
-(void)addTextField{
keyTextField = [[UITextField alloc] initWithFrame:CGRectMake((((self.view.frame.size.width)*5)/100), yAxisDistance, (((self.view.frame.size.width)*40)/100),(((self.view.frame.size.height)*8)/100))];
keyTextField.borderStyle = UITextBorderStyleRoundedRect;
keyTextField.placeholder = @"Key Value";
keyTextField.delegate = self;
mKeyTag+=1;
keyTextField.tag = mKeyTag;
[self.view addSubview:keyTextField];
valueTextField = [[UITextField alloc] initWithFrame:CGRectMake((((self.view.frame.size.width)*55)/100), yAxisDistance, (((self.view.frame.size.width)*40)/100),(((self.view.frame.size.height)*8)/100))];
valueTextField.borderStyle = UITextBorderStyleRoundedRect;
valueTextField.placeholder = @"Value";
valueTextField.delegate = self;
mValueTag+=1;
valueTextField.tag = mValueTag;
[self.view addSubview:valueTextField];
yAxisDistance = yAxisDistance+(((self.view.frame.size.height)*13)/100);
}
-(void)deleteTextField{
if (mKeyTag>=1000) {
UITextField *textField = (UITextField *)[self.view viewWithTag:mKeyTag];
[textField removeFromSuperview];
mKeyTag-=1;
yAxisDistance = yAxisDistance-35;
}
if (mValueTag>=2000) {
UITextField *textField = (UITextField *)[self.view viewWithTag:mValueTag];
[textField removeFromSuperview];
mValueTag-=1;
}
}
如果我点击添加它添加两个文本字段,一个用于键值,另一个用于该键的值。但是,如果我通过单击添加按钮5次添加5对文本字段并为这些文本字段提供一些值并尝试存储在字典中,它只存储最后的textfields值。但我想存储这5对文本字段中提供的所有数据。用于存储数据我正在使用以下代码
NSMutableDictionary *Dict = [[NSMutableDictionary alloc]init];
[Dict setValue:valueTextField.text forKey:keyTextField.text];
请帮忙,因为我对这个领域很陌生。
答案 0 :(得分:1)
如果你想让一个键有多个值,你想要的是一个字典,其值是一个可变数组,并继续为它添加值。
- (void)addValue:(id)value forKey:(id<NSCopying>)key
{
NSMutableArray *array = self.dictionary[key];
if (array == nil)
{
array = [NSMutableArray array];
self.dictionary[key] = array;
}
[array addObject:value];
}
答案 1 :(得分:0)
您的字典键必须是唯一的,否则可能会使用该键的新值覆盖这些值。
if(!dict) { //if no instance of the dict exists, create it
dict = [NSMutableDictionary new];
}
NSString *value = valueTextField.text; //grab your value
NSString *key = keyTextfield.text; //grab your key
//setting the value at this stage runs the risk of overwriting existing values for that key.
//[dict setValue:value forKey:key];
NSMutableArray *valuesForKeyArray = [NSMutableArray new]; //will hold your values for you
if ([dict valueForKey:key]) { //check if the dictionary already contains value for key
//dictionary contains values for the key already -> grab them
NSArray *existingValues = [NSArray arrayWithArray:[dict valueForKey:key]];
[valuesForKeyArray addObjectsFromArray:existingValues]; //add them in
}
//add the latest value
[valuesForKeyArray addObject:value];
//save into your dictionary (either the array with existing values + new value or just the new value)
[dict setValue:valuesForKeyArray forKey:key];
您创建字典(如果尚未在别处创建),抓取您的特定键和值,创建一个用于保存值的数组,检查字典是否已为该键保存了某些值,如果是 - &GT;你添加它们,然后将最新的值添加到数组并保存回你的字典。
使用此结构,您的字典键保持唯一,但不是只保留一个值,而是保存一组值。