创建和取消NSURLConnection [英] Creating and canceling an NSURLConnection

查看:119
本文介绍了创建和取消NSURLConnection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSURLConnection,当我允许负载完成工作正常。但是如果用户点击返回按钮,意味着webview将消失,我想取消正在进行的NSURLConnection。但是如果在viewWillDissapear被调用的时候有webview调用,然后我做:

I have a NSURLConnection that is working fine when I allow the load to complete. But if the user hits the back button, meaning the webview will dissappear, I want to cancel the NSURLConnection in progress. But if have the webview call into this class when viewWillDissapear is called, and then I do:

[conn cancel]

我得到一个NSINValidArgument异常。

I get an NSINValidArgument exception.

连接在.h文件中定义为实例数据:

The connection is defined as instance data in the .h file as:

NSURLConnection *conn;

异步从这里开始:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:articleURL]];

    if ([NSURLConnection canHandleRequest:request] && reachable) {
        // Set up an asynchronous load request
        conn = [NSURLConnection connectionWithRequest:request delegate:self];
        loadCancelled = NO;
        if (conn) {
            NSLog(@" ARTICLE is REACHABLE!!!!");
            self.articleData = [NSMutableData data];
        }
    }


推荐答案

你为什么会遇到异常的原因是你将一个autorelease对象保存到一个实例变量。

conn会在用户点击返回按钮时立即自动释放。之后,您调用cancel。因此,您有异常。

为了防止出现这种情况,您应该在将NSURLConnection对象保存在实例变量中时保留它。

The reason why you got the exception would be you are saving an autorelease object to an instance variable.
"conn" would be auto-released immediately when a user click back button. After that, you call cancel. Therefore, you had the exception.
To prevent this, you should retain NSURLConnection object when you keep it in an instance variable.

conn = [[NSURLConnection connectionWithRequest:request delegate:self] retain];

conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

不要忘记在dealloc方法中释放。

Don't forget to release this in the dealloc method.

这篇关于创建和取消NSURLConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆