deleting delegate on dealloc without an instance variable

so i start a ASIFormDataRequest on my [viewDidLoad] in a UIViewController.

ASIFormDataRequest *detailRequest = [ASIFormDataRequest requestWithURL:url];
detailRequest.delegate = self;
[detailRequest startAsynchronous];

If my UIViewController gets released before my Request finishes, my app crashes.

If i add my ASIFormDataRequest as an instance variable for example

@property(nonatomic, retain) ASIFormDataRequest *detailRequest;

and nil the delegate on dealloc

-(void)dealloc {
    if(self.detailRequest != nil) { self.detailRequest.delegate = nil; }
    self.detailRequest = nil;

    [super dealloc];
}

the app no longer crashes.

but i don't think it's necessary to create a instance variable just for this, especially if i have multiple requests.

is there a better way to do this?


I usually create an array and store all active requests in the array. When the request is completed I remove the request, and when the controller calls dealloc I cancel all of the requests and nil the delegate.


In order to release it you must have a pointer to it so yes, use an ivar. iars are not expensive.


By doing self.detailRequest = [ASIFormDataRequest requestWithURL:url]; I am guessing it is creating an autorelease object whose lifespan isn't bound to your controller class. If the creation and deletion of your object is bound to your controller, it's logical to use a instance variable.

More details about autorelease

链接地址: http://www.djcxy.com/p/30590.html

上一篇: 为什么NSURLConnection在发送多个请求时会超时?

下一篇: 在没有实例变量的情况下删除dealloc上的委托