I have a class written in a C object that does some work when connected to a network. This class does this work asynchronously, and the user gives a delegate that is called after the operation is completed (with a response if success or error fails). The delegate is called when there is no more work and the object can be freed.
Now I want to support a use case when a user releases an object of my class in a call to this delegate. This is quiet natural, since an instance of my class is not reused. Currently, when my call returns from a callback, he tries to continue working from where he left, only to find that he was released. Needless to say, application crashes at this point.
I know this can be done because the NSURLConnection class does just that. It is ok to release the connection object in the callback - (void)connectionDidFinishLoading:(NSURLConnection *)connection . How can i do the same?
EDIT:
Here is the code to understand it better:
@class MyRequest; @protocol MyDelegate - (void)completedRequest:(MyRequest*)request; @end @interface MyRequest : NSObject { id<MyDelegate> myDelegate; //variables... } - (id)init; - (id)initWithUrl:(NSString*)url delegate:(id<MyDelegate>)delegate; - (void)dealloc; - (void)fire; @property (nonatomic, readonly) bool fired; @property (nonatomic, readonly) NSInteger resultCode; @property (nonatomic, readonly) NSString *errorMessage; @end
The user creates a MyRequest object and sends a fire message. MyRequest uses NSURLConnection to do the job. When the response is received, I call the user specified by the delegate.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"In connectionDidFinishLoading..."); resultCode = RESULT_SUCCESS; [urlConnection release]; [urlRequest release]; if (myDelegate != nil) [myDelegate completedRequest:self]; }
source share