2

我正在尝试解析应用程序委托didFinishLaunchingWithOptions:方法的 xml 提要:

//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?谢谢。

4

2 回答 2

0

您将 XML 解析器塞进 AppDelegate 中是有原因的吗?毫无例外,我发现总是实例化一个解析器类来处理解析任务是有益的。例如...

myParser.h

@class parseClass;

@interface myXMLParser : NSObject <NSXMLParserDelegate> {

}

- (myXMLParser *) initmyXMLParser;

我的解析器

//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"
}
于 2013-07-20T02:35:33.863 回答
0

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

在使用 nsurlconnection 解析之前,您可能需要从 Web 下载 xml

于 2013-07-20T03:26:21.970 回答