【问题标题】:Cocoa - `stringWithContentsOfURL/dataWithContentsOfURL` causes ERROR?可可 - `stringWithContentsOfURL/dataWithContentsOfURL` 导致错误?
【发布时间】:2011-04-16 04:41:43
【问题描述】:

出于某种原因,以下代码可以正常工作。我已经检查了很多次 URL,这并不好笑(它返回我想解析的纯文本)。该代码 100% 正常运行,然后它停止工作并开始给我一个 EXC_BAD_ACCESS 错误。

调试输出中没有任何内容可以发布,除了一行说输出切换到进程两次。 (除了有时关于双重释放的事情。)

到目前为止(据我所知)我已经尝试过:

  • 重新安装应用程序 - 它仅在“默认”运行时出现问题(不是第一次运行/启动运行。)
  • 在浏览器中运行 URL(chrome、firefox、IE...)
  • 将调用放入 @try / @catch 块中
  • 使用retain
  • 使用临时 NSAutoreleasePool
  • 拆分/分离调用的元素(以及登录 Everything - 一旦遇到错误,就不会记录任何内容
  • 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];

NSAutoreleasePoolautorelease 由于http://discussions.apple.com/thread.jspa?threadID=1667544 而添加)

(兑现页面 - http://webcache.googleusercontent.com/search?q=cache:8D7zlQdG9PMJ:discussions.apple.com/thread.jspa%3FthreadID%3D1667544+http://discussions.apple.com/thread.jspa%3FthreadID%3D1667544&cd=1&hl=en&ct=clnk&gl=us&source=www.google.com

【问题讨论】:

  • 抱歉给您带来了困惑...自动释放/池是我试图帮助它不崩溃 - 它帮助它正确运行了两次(这就是我将它包含在帖子中的原因)
  • 在我们等待的时候,请注意[tmpPool retain] 应该是[tmpPool release]
  • 不错 - 但它永远不会到达那里
  • 我已经阅读了缓存的讨论。我无法重现您的问题,我不知道同步 URL 下载的错误,但我同意异步 URL 下载是推荐的方法。

标签: iphone objective-c cocoa file


【解决方案1】:

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 对象,因此您不会(自动)释放它。此外,第三个参数应该是&amp;er,而不是er

【讨论】:

  • Autorelease - 这是我在发布它时尝试的(尝试的东西 - 我改变了 **er -> *er 和 &er edit
  • @Wallter 我会在网站重新上线时回复。
【解决方案2】:

URLWithString 和 stringWithContentsOfURL 是方便的方法,然后已经将变量放入 autorelease 我认为您不需要在创建 the_URL 和 version_String 时添加 autorelease

尝试删除自动释放...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 2014-01-01
    • 1970-01-01
    • 2013-09-10
    • 2012-06-02
    • 2021-09-23
    • 1970-01-01
    相关资源
    最近更新 更多