大家好,我正在寻找一种方法将我的XML解析为几个标签," XMLReader" class是我的XML to Dictionary转换器的位置,它适用于我的所有其他视图。 和" getValue"是一种删除空格和制表符的方法。 现在当我尝试用数据提供标签时,我得到了这个异常:NSArray无法识别的选择器被发送到实例:0x ....
- (void)viewDidLoad
{
[super viewDidLoad];
NSDate* date = [NSDate date];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HHddMMyyyy"];
NSString* date_str = [formatter stringFromDate:date];
NSString *requestUrl = [NSString
stringWithFormat:@"xyz",date_str];
NSURL *staturl= [NSURL URLWithString:requestUrl];
NSURLRequest *statrequest = [NSURLRequest requestWithURL:staturl];
NSURLResponse *statresponse;
NSError *staterror;
NSData * statdata = [NSURLConnection sendSynchronousRequest:statrequest
returningResponse:&statresponse error:&staterror];
if (staterror) {
NSLog(@"URL Error");
}
NSString *statsdataAsString = [[NSString alloc]initWithData:statdata
encoding:NSASCIIStringEncoding];
NSDictionary *statsdictionary = [XMLReader dictionaryForXMLString:statsdataAsString
error:&staterror];
_stCreditlabel.text =[XMLReader getValue:[[[[statsdictionary
objectForKey:@"Statistics"]objectForKey:@"Statistics"]objectForKey:@"Statistic"]objectForKey:@"Name"]];
XML:
<Statistics xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="xyz">
<Statistics>
<Statistic>
<Name>heute</Name>
<Statistic>
<Name></Name>
<Value></Value>
</Statistic>
<Statistic>
<Name></Name>
<Value>518</Value>
</Statistic>
</Statistic>
<Statistic>
<Name>Allgemein</Name>
<Statistic>
<Name>Online</Name>
<Value>2458</Value>
</Statistic>
<Statistic>
<Name>Lager</Name>
<Value>444</Value>
</Statistic>
</Statistic>
</Statistics>
</Statistics>
日志:
2014-04-15 11:04:22.282 MConsole[763:60b] *** Terminating app due to uncaught
exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]:
unrecognized selector sent to instance 0x972ea70'
po 0x972ea70
<__NSArrayM 0x972ea70>(
{
Name = {
text = "\n \n \n heute";
};
Statistic = (
{
Name = {
text = "\n \n ";
};
Value = {
text = "\n 9";
};
text = "\n ";
},
{
Name = {
text = "\n \n ";
};
Value = {
text = "\n 518";
};
text = "\n ";
}
);
text = "\n ";
},
{
Name = {
text = "\n \n Allgemein";
};
Statistic = (
{
Name = {
text = "\n \n Online";
};
Value = {
text = "\n 2458";
};
text = "\n ";
},
{
Name = {
text = "\n \n Lager";
};
Value = {
text = "\n 444";
};
text = "\n ";
},
答案 0 :(得分:1)
行NSDictionary *statsdictionary = [XMLReader dictionaryForXMLString:statsdataAsString
error:&staterror];
返回NSArray,而不是NSDictionary,因此NSXMLParser崩溃,因为NSArray不知道任何名为object的对象的方法。
编辑:
在你的情况下,最后两行需要改为这样的(NB:UNTESTED!):
NSArray *statsArray = [XMLReader dictionaryForXMLString:statsdataAsString
error:&staterror];
_stCreditlabel.text = [[statsArray[0] valueForKey:@"Name"] valueForKey:@"text];
如果要访问statistic
数组中的更多statistics
元素,可以使用以下代码循环它们:
for (NSDictionary *statsObject in statsArray){
}
另外,我推荐本教程介绍如何解析iOS中的Xml:http://www.raywenderlich.com/725/xml-tutorial-for-ios-how-to-read-and-write-xml-documents-with-gdataxml。