ASIHTTPRequest / ASIFormDataRequest - referencing request object within blocks under ARC

南笙酒味 提交于 2019-11-28 06:24:33

(I read your comment to the other question)

After implementing a few more modules using ASIHTTPRequest, I learned that the best way was to keep a strong reference to your request object. In your case, you can do:

self.request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:SOME_URL]];
__weak ASIFormDataRequest *weakRequest = self.request; // __block directive not needed since we only access the instance's properties. 
[self.request setCompletionBlock:^{   

    if([weakRequest responseStatusCode] == 200)
    // ...

This way you can still control self.request even after you start the request (e.g. for cancelling). You can do self.request = nil; when you're ready to release your request, maybe inside your completion block or self.request's parent object's cleanup methods.

Update:

If you're targeting pre-iOS 5, then the common ground stands: use __unsafe_unretained instead of __weak. This is OK because looking at ASIHTTPRequest.m, the blocks are nil'ed out in its dealloc() (i.e. they shouldn't get executed). Although I haven't tested that yet, so make sure to still test with NSZombies enabled.

Note:

The only safe way to cancel an ASIHTTPRequest object is to call its clearDelegatesAndCancel method. I've been bitten by some nasty bugs when I was just using the plain cancel one.

If you're targeting iOS versions before 5.0, that do not include weak support:

__unsafe_unretained __block ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
Stephen Eilert

I've found this answer to be helpful: https://stackoverflow.com/a/7735770/133875

It says to use __unsafe_unretained as well as __block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!