Objective c 当我将Object设置为NSMutableDictionary时,先前添加的对象将被删除
这是将对象添加到NSMutableDictionary的代码:Objective c 当我将Object设置为NSMutableDictionary时,先前添加的对象将被删除,objective-c,ios7,nsmutabledictionary,Objective C,Ios7,Nsmutabledictionary,这是将对象添加到NSMutableDictionary的代码: -(void)mapUserFields: (UIControl *) sender { nsd = [[NSMutableDictionary alloc]init]; int tagValue = sender.tag; UITextField *field = [sender viewWithTag: tagValue]; [nsd setObject:field.text forKey:[NSString stri
-(void)mapUserFields: (UIControl *) sender {
nsd = [[NSMutableDictionary alloc]init];
int tagValue = sender.tag;
UITextField *field = [sender viewWithTag: tagValue];
[nsd setObject:field.text forKey:[NSString stringWithFormat:@"%d", tagValue]];
NSLog(@"\nfield.text: %@ tagValue: %d nsd.count: %d\n",field.text, tagValue, nsd.count);
}
这是调试器控制台的输出:
2014-09-17 15:18:10.022 Books[20738:60b]
field.text: 2 tagValue: 0 nsd.count: 1
2014-09-17 15:18:11.394 Books[20738:60b]
field.text: 4 tagValue: 1 nsd.count: 1
2014-09-17 15:18:16.918 Books[20738:60b]
field.text: 6 tagValue: 2 nsd.count: 1
2014-09-17 15:18:18.863 Books[20738:60b] dictionary.count: 1
如您所见,计数保持为1,但数据有效。有什么问题,我该如何解决?正如上面Josh所指出的,这一行是您的问题:
nsd = [[NSMutableDictionary alloc]init];
因为它用一本新词典替换了整个词典。所以,这并不是说添加一个键就是删除另一个键,而是明确地丢弃了早期的数据
或许可以尝试:
if (nds == nil) {
nsd = [[NSMutableDictionary alloc]init];
}
您已全局声明NSMutableDictionary“nsd”,并且每当触发某个控制事件时,您都在分配内存并初始化字典。您可以在视图控制器的viewDidLoad方法中初始化字典,而不是每次初始化字典
- (void)viewDidLoad
{
[super viewDidLoad];
nsd = [[NSMutableDictionary alloc]init];
}
然后在方法中将对象添加到字典中
- (void)mapUserFields:(UIControl *) sender
{
int tagValue = sender.tag;
UITextField *field = [sender viewWithTag: tagValue];
[nsd setObject:field.text forKey:[NSString stringWithFormat:@"%d", tagValue]];
NSLog(@"\nfield.text: %@ tagValue: %d nsd.count: %d\n",field.text, tagValue, nsd.count);
}