不调用委托方法,并且parse属性始终为FALSE

时间:2013-07-20 01:49:09

标签: ios nsxmlparser nsxmlparserdelegate

我正在尝试解析应用委托didFinishLaunchingWithOptions:方法的xml Feed:

//Parse XML Data
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://xxxxxxxxxxxxxxxxx/xml"]];//url is just fine :)
    [xmlParser setDelegate:self];
    BOOL parseState = [xmlParser parse];
    if (parseState) {
        NSLog(@"parse succeeded");
    }else{
        NSLog(@"parse failed");//Always parse failed, parse is always "NO"
    }

委托协议方法(无人调用):

#pragma mark - NSXMLParserDelegate

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
    NSLog(@"parser:didStartElement:namespaceURI:qualifiedName:attributes:");

}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{

    NSLog(@"parser:foundCharacters:");
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    NSLog(@"parser:didEndElement:namespaceURI:qualifiedName:");


}

当然,AppDelegate.h符合NSXMLParserDelegate协议:

@interface AppDelegate : UIResponder <UIApplicationDelegate,NSXMLParserDelegate>

我错过了什么?为什么不调用协议方法以及为什么[xmlParser parse]总是返回NO?感谢名单。

2 个答案:

答案 0 :(得分:0)

您是否有理由在AppDelegate中填写XML解析器?毫无例外,我发现总是实例化一个解析器类来处理解析任务是有益的。例如......

myParser.h

@class parseClass;

@interface myXMLParser : NSObject <NSXMLParserDelegate> {

}

- (myXMLParser *) initmyXMLParser;

myParser.m

//I do my instantiating like this so it can only be done once
//If you need to instantiate the class more than once do NOT use dispatch_once!
- (myXMLParser *)initmyXMLParser
{
    static myXMLParser *newInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        newInstance = [[myXMLParser alloc]init];
    });
    return newInstance;
}
//include other delegate methods as well

AppDelegate.m

#import "myParser.h"

NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL      URLWithString:@"http://xxxxxxxxxxxxxxxxx/xml"]];//url is just fine :)
myXMLParser *theParser = [[myXMLParser alloc]initmyUpdateXMLParser];
[xmlParser setDelegate:theParser];
BOOL parseState = [xmlParser parse];
if (parseState) {
    NSLog(@"parse succeeded");
}else{
    NSLog(@"parse failed");//Always parse failed, parse is always "NO"
}

答案 1 :(得分:0)

可能是ARC错误,尝试将xmlparser设置为强属性,以便在解析文件之前不会释放它。

您可能希望在使用nsurlconnection

解析xml之前从Web下载xml