Iam消耗XML响应并解析它。但是当我将对象添加到NSMutableDictionary然后再添加到nSMutableArray时,响应为null。我无法理解iam出错的地方? 我的Xmlresponse是这样的:
<List>
<Address>
<City>Michigan</City>
<Line1>17</Line1>
<line2>12</Line2>
</Address>
<Employee>
<EmployeeName>Williams</EmployeeName>
</Employee>
<Address>
<City>NewYork</City>
<Line1>27</Line1>
<line2>52</Line2>
</Address>
<Employee>
<EmployeeName>Mandarin</EmployeeName>
</Employee>
我的回答应该是这样的:
Michigan
17
12
Williams
NewYork
27
52
Mandarin
我的解析代码是这样的:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI: (NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
element = elementName;
if([elementName isEqualToString:@"Address"])
{
arr=[[NSMutableArray alloc] init];
drr=[[NSMutableDictionary alloc] init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
[srr appendString:string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:@"City"])
{
[drr setObject:srr forKey:@"City"];
[srr release],srr=nil;
return;
}
if([elementName isEqualToString:@"Line1"])
{
[drr setObject:srr forKey:@"Line1"];
[srr release],srr=nil;
return;
}
if([elementName isEqualToString:@"Line2"])
{
[drr setObject:srr forKey:@"Line2"];
[srr release],srr=nil;
return;
}
if([elementName isEqualToString:@"Address"])
{
[arr addObject:drr];
[drr release],drr=nil;
}
[srr release],srr=nil;
}
NsLog(@"%@",arr);
但是当我在'arr'检查响应时它会返回NULL吗?Y是这样的吗?我哪里错了?
答案 0 :(得分:0)
请在viewDidLoad中初始化您的iVars
arr=[[NSMutableArray alloc] init];
drr=[[NSMutableDictionary alloc] init];
,因为
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI: (NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
解析每个元素时会调用,因此会再次重新分配