开发者

Confused on using Class method with an object that has a delegate

I'm confused on Delegates. I was always under the impression that if you didn't set a delegate than it wouldn't respond to delegate callbacks. I have a crash with a Class method that releases its object.

Lets say I have a object "Something" that has a delegate set-up for handling results to the callers that care. Something uses ASIHTTPRequest to do some posts / gets asynchronously.

-(void)somethingHasResults{开发者_运维百科

 //something needs to tell its listeners that its has completed (pseudo-code)

 if([delegate respondsToSelector:@selector(somethingDidComplete)]){

   [delegate somethingDidComplete];

 }

}

But I also have a Helpers.h/.m with a series of class methods like so...

+(void)shoutItOutLoud{

  //doesn't need a delegate, doesn't need a response -- just do your thing and exit

  Something *something = [[Something alloc] init];

  [something shouldDoSomethingAwesomeButDoesntNeedToRespond];

  [something release];

}

When I use [Helpers shoutItOutLoud] I get a crash. Now the crash is actually in ASIHttpRequest.m's reportFinished, but following the trace brings me all the way back to my class method which is releasing the object before completion.

The whole point of this is that I'm surprised that I have a crash here and I'm trying to wrap my head around this. A co-worker and I got into a discussion and he says its because I'm releasing my object so the delegate is pointing at garbage. This seems wrong to me, as this class method doesn't receive the responses anyways?


I believe your problem is actually to do with not cleaning the ASIHttpRequest delegate: an ASIHttpRequest object sets its delegate to the object is called from.

So you will need to clear that delegate as well (in the Something class). Assuming that you have a property of type ASIHttpRequest, here is what I do in the dealloc method:

- (void)dealloc {

...
[_request clearDelegatesAndCancel];
[_request release];
[super dealloc];

}

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜