【发布时间】:2017-12-13 09:16:59
【问题描述】:
我有一个视图控制器,我在其中解析 xml 文件并在字典中获取其值,我试图获取标签中的值,但我的应用程序因显示此错误而崩溃*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString objectForKey:]: unrecognized selector sent to instance 0x10256a1b0'
我从字典中获取值的代码是这些,
NSLog(@"string: %@", str);
NSDictionary *xmlDoc = [NSDictionary dictionaryWithXMLString:str];
NSLog(@"dictionary: %@", xmlDoc);
for (NSDictionary * oneCustomer in xmlDoc)
{
// Create a new Customer record
_lblID.text = [oneCustomer objectForKey:@"_id"];
NSLog(@"Reg: %@ ",_lblID.text);
_lblAlert.text = [oneCustomer objectForKey:@"_topic"];
NSLog(@"Make: %@ ",_lblAlert.text);
_lblxref.text = [oneCustomer objectForKey:@"xref"];
NSLog(@"Type: %@ ",_lblxref.text);
_lbltext.text = [oneCustomer objectForKey:@"text"];
NSLog(@"Model: %@ ", _lbltext.text);
_lblgraphic.text = [oneCustomer objectForKey:@"explanation"];
NSLog(@"Model: %@ ",_lblgraphic.text);
_lblprompt.text = [oneCustomer objectForKey:@"prompt"];
NSLog(@"Model: %@ ",_lblprompt.text);
_lblvoice.text = [oneCustomer objectForKey:@"_id"];
NSLog(@"Model: %@ ", _lblvoice.text);
//roils = [oneCustomer objectForKey:@"recommended oil"];
//NSLog(@"Model: %@ ",roils);
}
如何消除此错误? 这是我的字典,
dictionary: {
"__name" = QF;
"_category" = "C&M";
"_id" = AB2001;
"_ni_exempt" = no;
"_topic" = Alertness;
answers = {
answer = (
{
"_correct" = no;
text = "give an arm signal as well as using your indicators";
},
{
"_correct" = no;
text = "signal so that other drivers can slow down for you";
},
{
"_correct" = yes;
text = "look over your shoulder for a final check";
},
{
"_correct" = no;
text = "select a higher gear than normal";
}
);
};
question = {
explanation = {
text = "If you want to make a U-turn, slow down and ensure that the road is clear in both directions. Make sure that the road is wide enough to carry out the manoeuvre safely.";
voice = {
"_id" = "AB2001-2";
};
};
prompt = "Mark one answer";
text = "Before you make a U-turn in the road, you should";
voice = {
"_id" = "AB2001-1";
};
xref = "DES s4, DES s9, HC r159-161";
};
我必须从这本字典中提取所有值我怎样才能得到这个?
【问题讨论】:
-
显然在某些时候
oneCustomer是一个NSString对象,而不是NSDictionary,所以你不能对它执行[oneCustomer objectForKey:someKey]并导致崩溃。 -
那么现在该如何解决呢?如何从字典中获取值? @Larme
-
这不是字典。你能给我们
str的值吗?我有一些猜测,比如为什么 for 循环......所以_lblID.text = [xmlDoc objectForKey:@"_id"];而不是_lblID.text = [oneCustomer objectForKey:@"_id"];(等等),但这是疯狂的猜测...... -
我已经添加了字典,请检查它。@Larme
-
删除
for (NSDictionary * oneCustomer in xmlDoc),然后只做_lblID.text = [xmlDoc objectForKey:@"_id"];(等等,将oneCustomer替换为xmlDoc。
标签: ios objective-c