开发者

How to allow the object to be released on callback?

I have a class written in objective C which does some work by connecting to the network. This class does this work in async manner and user gives a delegate which is called once the operation is finished (with response if success or error if failure). The delegate is called when there is no more work to do and object can be released.

Now I want to support a use-case when user will release the object of my class in the call to that delegate. This is quiet natural since instance of my class are not reusable. Currently when my call returns from callback, it tries to continue from where it left only to find that it has been released. Needless to say, application crashes at that point.

I know it can be done because NSURLConnection class does just that. It is OK to release the connection object in the callback - (void)connectionDidFinishLoading:(NSURLConnection *)connection. How can I accomplish the same?

EDIT:

Here is 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

User creates the object of MyRequest and sends fire message. MyRequest internally uses NSURLConnection to do the work. When the response is received, I call the user given delegate.

- (void)connectionDidFinishLoading:(NS开发者_开发问答URLConnection *)connection
{
    NSLog(@"In connectionDidFinishLoading...");

    resultCode = RESULT_SUCCESS;
    [urlConnection release];
    [urlRequest release];

    if (myDelegate != nil)
        [myDelegate completedRequest:self];
}


Just add [[self retain] autorelease] before you invoke the delegate callback to extend your object's lifetime. This will cause it to be released later so you can finish up.

Another approach is to use performSelectorOnMainThread method of NSObject. performSelector... machinery will retain your object, call the method, and then release it afterwards. If you make the performSelector method wait until finished, then you'll have the same problem you do now, since you'll get deallocated during that call. If you don't wait until it is finished, then you shouldn't have a memory issue, but then you can't do anything after it's done. If that's acceptable, then you should be fine.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜