NSLog字符串很好,但是UITextView中的字符串会导致异常

时间:2013-06-24 08:46:27

标签: ios objective-c tfhpple

所以我有一个视图控制器,在viewdidload方法中它应该从网页加载一些内容(只是一个概念证明,它最终会被缓存)。它使用tfhipple库获取内容并将内容放入数组中,它将数据记录到控制台,然后我希望它将内容应用于UITextView。但是,当调用视图控制器时,它甚至将文本记录到控制台,但在它将其设置为UITextView的内容的行上会导致异常。

NSData *dataURL;
NSString *url = @"http://www.testwebsite.com/testpage.html";
dataURL =  [NSData dataWithContentsOfURL: [NSURL URLWithString: url]];

NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];

TFHpple * doc       = [[TFHpple alloc] initWithHTMLData:dataURL];

NSArray *elements  = [doc searchWithXPathQuery:@"//div[contains(@id,'main-section')]//text()"];

NSString * aboutcontents = [elements objectAtIndex:2];
NSLog(@"test: %@", aboutcontents);
self.aboutbox.text = aboutcontents;

它导致的异常如下,以及之前的控制台输出:

2013-06-24 09:37:51.433 AppName[24765:c07] test: {
    nodeContent = "Test Content";
    nodeName = text;
    raw = "Test Content";
}
2013-06-24 09:37:51.434 AppName[24765:c07] -[TFHppleElement length]: unrecognized selector sent to instance 0x8043be0
2013-06-24 09:37:51.434 AppName[24765:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TFHppleElement length]: unrecognized selector sent to instance 0x8043be0'
*** First throw call stack:
(0x25d012 0x16ebe7e 0x2e84bd 0x24cbbc 0x24c94e 0x76b4fb 0x3347 0x7111c7 0x711232 0x7328c9 0x732704 0x730bda 0x730a5c 0x732647 0x16ff705 0x6332c0 0x633258 0x855ff4 0x16ff705 0x6332c0 0x633258 0x6f4021 0x6f457f 0x6f4056 0x859af9 0x16ff705 0x6332c0 0x633258 0x6f4021 0x6f457f 0x6f36e8 0x662cef 0x662f02 0x640d4a 0x632698 0x22b2df9 0x22b2ad0 0x1d2bf5 0x1d2962 0x203bb6 0x202f44 0x202e1b 0x22b17e3 0x22b1668  0x62fffc 0x2fdd 0x21a5)
libc++abi.dylib: terminate called throwing an exception
(lldb) 

我为什么会这样做有点困惑。如果我手动将字符串aboutcontents设置为某个内容,则会更改UITextView的内容而不会出现问题。

任何帮助都一如既往地受到赞赏。

3 个答案:

答案 0 :(得分:2)

试试这个:

TFHppleElement * aboutcontents = [elements objectAtIndex:2];
NSLog(@"test: %@", [aboutcontents text]);
self.aboutbox.text = [aboutcontents text];

以下是从hpple获取的文档部分:

TFHppleElement * element = [elements objectAtIndex:0];
[e text];                       // The text inside the HTML element (the content of the  first text node)
[e tagName];                    // "a"
[e attributes];                 // NSDictionary of href, class, id, etc.
[e objectForKey:@"href"];       // Easy access to single attribute
[e firstChildWithTagName:@"b"]; // The first "b" child node

尝试获取示例属性并查看它返回给您的内容。

答案 1 :(得分:1)

试试这个。

NSDictionary * aboutcontents = [elements objectAtIndex:2];
NSLog(@"test: %@", aboutcontents);
self.aboutbox.text = [aboutcontents objectForKey:@"nodeContent"];

我不明白上下文,但是我在日志中看到了{},我想只有字典才会被打印出来。

答案 2 :(得分:1)

你获得NSString * aboutcontents = [elements objectAtIndex:2];的resutt是一本字典,将字典转换成字符串就像这样

NSString * aboutcontents=[NSString stringWithFormat:@"%@",[elements objectAtIndex:2]];