so i start a ASIFormDataRequest on my [viewDidLoad] in a UIViewController.
ASIFormDataRequest *detailRequest = [ASIFormDataRequest requestWithURL:url];
detailRequest.delegate = self;
[detailRequ开发者_C百科est 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
You could do this:
detailRequest.delegate = [self retain];
and then call
[self autorelease];
In the ASIFormDataRequest callback method. That's what I generally tend to do, anyway.
That way, the request object retains its delegate for the duration of the request.
As this is the Asynchronous request so if you set delegate it means as soon as response comes your delegate methods will be called. Till that time your object should be alive to handle the response. So making it retain and releasing in the dealloc is fine and before than that you have to set delegate to nil. So that if response comes after releasing the method, framework should not be misguided to search for method of dead object.
To handle multiple request the best way is to create the array and number of objects you want to use. When you are done with the objects, in dealloc method iterate through each object and set delegate nil and release the object.
精彩评论