我正在尝试将特定名称的元素添加到NSMutableArray中,我从XML文件中获取该元素。我是在追逐元素。这里的第一个NSLog输出正确:
Found an element named: image with a value of: http://media.giantbomb.com/uploads/1/10353/2320941-untitledb_tiny.jpg
第二个NSLog正确输出:
I'm about to try adding a game called Bayonetta 2 to the array
第三个NSLog总是告诉我数组中没有条目。我没有在[_listOfGameNames addObject: element];
行上收到任何错误,所以我不知道它为什么不将它添加到数组中。
对我有什么想法?这是完整的代码:
- (void) searchWithString: (NSString *)string {
NSString *searchString = [NSString stringWithFormat: @"http://api.giantbomb.com/search/?api_key=MYKEY12345BLAHBLAH&resources=game&format=xml&query=%@", string];
NSURL *searchURL = [NSURL URLWithString: searchString];
parser = [[NSXMLParser alloc] initWithContentsOfURL: searchURL];
[parser setDelegate:self];
[parser parse];
// NSLog(@"XMLParser just reached the end of its initWithString method. The string was %@", searchURL);
NSLog(@"There are %u elements in the List Of Game Names array", [_listOfGameNames count]);
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
element = [NSMutableString string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
NSLog(@"Found an element named: %@ with a value of: %@", elementName, element);
if ([elementName isEqualToString:@"name"]) {
NSLog(@"I'm about to try adding a game called %@ to the array", element);
[_listOfGameNames addObject: element];
NSLog(@"I added an element to the array, making a total of %u", [_listOfGameNames count]);
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if(element == nil) element = [[NSMutableString alloc] init];
[element appendString:string];
}
答案 0 :(得分:0)
答案:没有初始化可变阵列!
答案 1 :(得分:0)
您需要初始化数组。你可以实现Getter。
-(NSMutableArray *) listOfGameNames
{
if(!_listOfGameNames){
_listOfGameNames = [[NSMutableArray alloc] init];
}
return _listOfGameNames;
}