【问题标题】:program terminating with uncaught exception of type NSException程序以 NSException 类型的未捕获异常终止
【发布时间】:2018-12-04 00:08:56
【问题描述】:

我正在尝试浏览一个 xml 文件并显示内容

    int main(int argc, const char * argv[])
    {
    NSString *xmlPath = [[NSBundle mainBundle] pathForResource:@"xml" ofType:@"xml"];
    NSString *xml = [NSString stringWithContentsOfFile:xmlPath encoding:NSUTF8StringEncoding error:nil];
    NSXMLDocument *xmlDocument = [[NSXMLDocument alloc] initWithXMLString:xml options:0 error:nil];
    NSMutableArray *array = [NSMutableArray array];

    for (NSXMLElement *node in [xmlDocument.rootElement nodesForXPath:@"//app" error:nil])
    {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        NSMutableArray *photos = [NSMutableArray array];

        for (NSXMLElement *subNode in node.children)
        {
            if ([subNode.name isEqualToString:@"address"])
                [photos addObject:subNode.stringValue];
            else
                [dict setObject:subNode.stringValue forKey:subNode.name];
        }

        [dict setObject:photos forKey:@"address"];
        [array addObject:dict];
    }

    NSLog(@"%@", array);
    return 0;

}

但我在这一行中遇到错误

NSXMLDocument *xmlDocument = [[NSXMLDocument alloc] initWithXMLString:xml options:0 error:nil];

错误说 libc++abi.dylib:以 NSException 类型的未捕获异常终止 (lldb)

请帮忙

【问题讨论】:

  • 显示您在控制台中收到的整个错误消息。它应该为您的问题提供有用的提示。你确定xml 不为零吗?如果是这种情况,那么使用您拥有的error 参数呢?

标签: objective-c xml xcode macos


【解决方案1】:

检查 xml NSString 是否为 nil

【讨论】:

  • @BharathSuresh 按照我说的做:与其写error:nil,不如使用那个参数?
【解决方案2】:

从本地路径读取

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0];
 NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"xml.xml"];

然后从本地路径使用

NSURL *xmlFile = [NSURL fileURLWithPath:appFile];
 NSXMLParser *addressParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlFile];

注意:NSXMLDocument 是仅 OS X 的类

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSXMLDocument_Class/Reference/Reference.html

你不能在 iOS 中使用它。

在 iOS 上,您可以使用 NSXMLParser

【讨论】:

  • 我没有在 iOS 上尝试这个。我希望它仅适用于 OS X。
猜你喜欢
  • 2016-03-25
  • 1970-01-01
  • 2017-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-20
  • 2014-07-26
相关资源
最近更新 更多