我有一个按钮,其标题是我从服务器
获得的响应中选择的获得的答复如下:
[
{"Id":"2","Name":"Alex"},
{"Id":"5","Name":"AMark"},
{"Id":"1","Name":"Karta"},
{"Id":"7","Name":"Juan"},
{"Id":"6","Name":"Honky"},
{"Id":"3","Name":"Nirauk"},
{"Id":"4","Name":"Chinua"}
]
设置按钮标题的代码如下:
_ButtonArray =[[NSArray alloc]initWithObjects:self.b1,self.b2,self.b3,self.b4,self.b5,self.b6, nil];
-(void)getList:(NSData *)response
{
NSArray* Array = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@", Array);
for (UIButton *button in _ButtonArray) {
NSLog(@"the tag of button is %ld",(long)button.tag);
for (NSDictionary* dict in Array)
{
if ([[dict objectForKey:@"Id"] intValue] == button.tag)
{
[button setTitle:[dict objectForKey:@"Name"] forState:UIControlStateNormal];
NSLog(@"the Id is %@",[dict objectForKey:@"Id"]);
}
}
}
}
但它崩溃并给出了这个例外:
“因未捕获的异常而终止应用程序'NSInvalidArgumentException',原因:' - [__ NSCFString objectForKey:]:无法识别的选择器发送到实例0x7b24a7f0”
我无法理解我哪里出错了。请提出错误建议。
NSLog的结果:
(
{
Id = 2;
Name = Alex;
},
{
Id = 5;
Name = AMark;
},
{
Id = 1;
Name = Karta;
},
{
Id = 7;
Name = Juan;
},
{
Id = 6;
Name = Honky;
},
{
Id = 3;
Name = "Nirauk";
},
{
Id = 4;
Name = "Chinua";
}
)
答案 0 :(得分:1)
您能否再次确认您的回复格式?是你有上面提到的dict数组,或者它可能有Dict => Array => Dict例如
{
[
{...}
]
}
修改:
我执行了你的代码:
函数工作正常,我认为问题在于将响应字符串转换为NSData
NSString *responseString = @"[{"Id":"5","Name":"AMark"}, {"Id":"1","Name":"Karta"}]";
//您的回复字符串
NSData *data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
[self getList:data];
//你的函数调用
这段代码没有崩溃。