How to allow the release of an object in a callback?

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]; } 
+3
source share
1 answer

Just add [[self retain] autorelease] before you invoke the delegate callback to extend the life of your object. This will cause it to be released later in order to complete the work.

Another approach is to use the performSelectorOnMainThread NSObject method. The performSelector... mechanism performSelector... save your object, call the method, and then release it later. If you make the performSelector method until you finish, you will have the same problem as now, since you will get free during this call. If you did not wait for completion, then you should not have problems with memory, but after that you can not do anything. If this is acceptable, then you should be fine.

+4
source

All Articles