Maciej Trybiło
Maciej Trybiło

Reputation: 1207

How to implement a class method with a block completion handler

I'm trying to implement a fire-and-forget class method similar to

+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler

in the NSURLConnection, but I'm slightly confused about the memory management (I'm NOT using ARC at the moment).

My current code goes like this:

@interface StuffInfoDownloader() <UIAlertViewDelegate>

typedef void (^StuffInfoDownloaderCompletionBlock)(NSArray *stuffs);

- (id)initStuffsWithIdentifiers:(NSSet *)identifiers
         completionHandler:(void (^)(NSArray *stuffs))handler;

@property (retain, nonatomic) StuffInfoDownloaderCompletionBlock completionHandler;
@property (retain, nonatomic) NSSet *identifiers;

@end

@implementation StuffInfoDownloader

@synthesize completionHandler = _completionHandler;
@synthesize identifiers = _identifiers;

+ (void)loadAsynchronouslyWithIdentifiers:(NSSet *)identifiers
                    completionHandler:(void (^)(NSArray *stuffs))handler
{
    StuffInfoDownloader *downloader = [[StuffInfoDownloader alloc] initStuffsWithIdentifiers:identifiers completionHandler:handler];

    [downloader downloadStuffs];
    [downloader release]; // will retain itself
}

- (id)initStuffsWithIdentifiers:(NSSet *)identifiers
          completionHandler:(void (^)(NSArray *stuffs))handler
{

    if (!(self = [super init])) {
        return nil;
    }

    [self retain];

    _completionHandler = handler;
    _identifiers = identifiers;

    return self;
}

- (void)downloadStuffs
{
    __block StuffInfoDownloader *me = self; // avoid reference cycle between self and the block
    [StuffsConnection loadAsynchronouslyWithIdentifiers:self.identifiers completionHandler:
    ^(NSArray *stuffs, NSError *error) {
         if(error) {
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection Failed."
                                                         message:@"TODO do localised string"
                                                        delegate:self cancelButtonTitle:@"OK"
                                               otherButtonTitles:nil, nil];
             [alert show];
             [alert release];
         } else {
             me.completionHandler(stuffs);
             [self release];
         }
    }];
}

#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
#pragma unused(alertView, buttonIndex)
    // try again
    [self downloadStuffs];
}

- (void)dealloc
{
    [_completionHandler release];
    [_identifiers release];
    [super dealloc];
}

Basically, I'm passing ownership of the object to itself, and releasing it in the handler. Any problems with that?

Upvotes: 0

Views: 2614

Answers (2)

newacct
newacct

Reputation: 122518

There are so many things wrong with this code. Besides the block property needing to be copy. You shouldn't do the [self retain]; and [self release]; (p.s. you missed a [self release] in the error case). That completely goes against the memory management rules. They are completely unnecessary if you do things right. Memory management in Cocoa is completely local -- a function or method needs only care what it does, not what any other code does. init has no reason to do [self retain], and does not have to "worry" about what any other code does. Period.

Then the _completionHandler = handler; _identifiers = identifiers; are wrong. The block needs to be copied if you are storing it in an instance variable; and the set needs to be retained or copied. You need to do either _completionHandler = [handler copy]; _identifiers = [identifiers retain]; or use the setter self.completionHandler = handler; self.identifiers = identifiers;.

Then, there is no issue of "retain cycle". A retain cycle requires a cycle -- A retains B, and B retains A. The block retains self, but does self retain the block? I don't see that anywhere. You are simply calling a class method of another class on this block. So you shouldn't do the weak reference. The weak reference is not correct anyway, since there is no guarantee that the current object will be valid by the time the block executes.

It seems that you (incorrectly) did the whole [self retain] thing, all in order to deal with the fact that you (also incorrectly) did not allow the block to retain self, as it should. Just get rid of this weak reference stuff, and get rid of the [self retain] stuff, and then it will not only follow the memory management rules, be more robust, but also look cleaner, simpler, and more understandable.

Upvotes: 1

Mr Bonjour
Mr Bonjour

Reputation: 3400

@property (nonatomic, copy) StuffInfoDownloaderCompletionBlock
completionHandler;

then in init:

self.completionHandler = handler;

You should never retain block if u haven't copied it before, that doesn't make sense .

By the way

 if ((self = [super init])) {
    /* initialization stuff*/
    }


 return self;

Seems that your code has lot of retainCycle flaws design

Upvotes: 0

Related Questions