Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C: How to release delegates in this situation

I am using custom delegate objects to do some cleanup tasks after a request finishes. ASIHTTPRequest doesn't retain delegates so I can't autorelease them. Right now this is how I am allocating and releasing the delegates.

App Delegate

MyDelegate *delegate = [[MyDelegate alloc] init];   
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:delegate];

MyDelegate.m

- (void)requestFinished:(ASIHTTPRequest *)request
{
    [self release];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    [self release];
}

Is there a better way to do this? Having the delegates release themselves seems ugly and Xcode's build and analyze feels uncomfortable with what I'm doing.

like image 589
David Avatar asked Jan 05 '11 22:01

David


2 Answers

A simple approach would be to maintain a mutable set of delgates for each active request in your main controller (the app delegate, in this case):

@interface MyAppController
{
    NSMutableSet * activeDelegates;
}
@end

@implementation MyAppController

- (id)init
{
    if ((self = [super init]) == nil) { return nil; }
    activeDelegates = [[NSMutableSet alloc] initWithCapacity:0];
    return self;
}

- (void)dealloc
{
    [activeDelegates release];
}

- (void)createRequest
{
    MyDelegate *delegate = [[MyDelegate alloc] init];
    [activeDelegates addObject:delegate];
    [delegate release];

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];

    ...
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    MyDelegate *delegate = [request delegate];
    [delegate doSomething];
    [activeDelegates removeObject:delegate];
{

- (void)requestFailed:(ASIHTTPRequest *)request
{
    [activeDelegates removeObject:[request delegate]];
}

@end
like image 156
e.James Avatar answered Oct 16 '22 23:10

e.James


Why do you have a separate class purely to be a delegate? That's not how delegate objects typically work. Normally the controller that created the ASIHTTPRequest becomes the delegate, at which point you don't have to worry about releasing it because it will outlive the ASIHTTPRequest already (and if your controller gets dealloced before the ASIHTTPRequest is done, you need to cancel the request).

like image 22
Lily Ballard Avatar answered Oct 16 '22 23:10

Lily Ballard