由于某种原因,以下代码有时可以工作。我已经检查了很多次 URL,这并不有趣(它返回我想要解析的纯文本)。该代码 100% 正常工作,然后它停止工作并开始给我一个 EXC_BAD_ACCESS
错误。
除了一行表示输出切换到进程两次之外,调试输出中没有任何内容可发布。 (除了有时有关双重发布的事情。)
到目前为止(据我所知)我已经尝试过:
- 重新安装应用 - 仅在“默认”运行(而不是第一次运行/启动运行)时出现问题。
- 在浏览器(chrome、firefox、IE...)中运行 URL
- 将调用放入
@try/@catch
block - 使用
保留
- 使用临时
NSAutoreleasePool
- 拆分/分离调用的元素(以及登录一切 - 一旦遇到错误,就不会记录任何内容)
- 将
dataWithContentsOfURL
函数与上述函数结合使用
NSAutoreleasePool *tmpPool = [[NSAutoreleasePool alloc] init];
NSString *url_string = [self getNormalVersionDownloadURL];
NSLog(@"urlString: -%@-", url_string);
NSError *er;
NSURL *the_URL = [[NSURL URLWithString:url_string] retain];
NSString *version_String = [NSString stringWithContentsOfURL:the_URL encoding:NSASCIIStringEncoding error:&er];
NSLog(@"verions_string: -%@-", version_String);
if ([version_String length] < 16)
return;
[tmpPool release];
(由于 http://discussions.apple.com/thread.jspa?threadID=1667544 添加了 NSAutoreleasePool
和 autorelease
)
最佳答案
discussions.apple.com 目前已关闭,因此我无法阅读讨论主题。无论如何:
<小时/>NSString *url_string = [[self getNormalVersionDownloadURL] autorelease];
-getNormalVersionDownloadURL
返回拥有的还是非拥有的对象?如果该方法返回一个拥有的对象,则仅发送 -autorelease
。
NSError **er;
这应该是 NSError *er
相反,或者应该使用 NSError *
类型的变量的地址进行初始化。由于后者不常见且不必要,因此以下假设为 NSError *er
。
NSURL *the_URL = [[NSURL URLWithString:url_string] autorelease];
+URLWithString:
返回一个不属于您的 NSURL
对象,因此您不会(自动)释放它。
version_String = [[NSString stringWithContentsOfURL:the_URL
encoding:NSASCIIStringEncoding error:er] autorelease]; //ERROR occurs here
两个问题::+stringWithContentsOfURL:
返回一个您不拥有的 NSString
对象,因此您不会(自动)释放它。此外,第三个参数应该是 &er
而不是 er
。
关于iphone - cocoa - `stringWithContentsOfURL/dataWithContentsOfURL` 导致错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5684519/