开发者

Creating and canceling an NSURLConnection

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 t开发者_StackOverflow中文版he NSURLConnection in progress. But if have the webview call into this class when viewWillDissapear is called, and then I do:

[conn cancel]

I get an NSINValidArgument exception.

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

NSURLConnection *conn;

The async is initiated here:

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];
        }
    }


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];

or

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜