Emin Israfil iOS
Emin Israfil iOS

Reputation: 1811

Am I using this block correctly?

Question: Am I using this block correctly? No leaks or retain cycles?

Question 1.5: Is this good style or should I just do an inline block?

typedef void(^completionBlock)(void);

...

-(completionBlock)completionBlock{
    return ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:kFetchNewTopicsAndReloadTableData object:nil];
    };
}

..

-(void)refresh
{
    [self dismissViewControllerAnimated:YES completion:[self completionBlock]];
}

Upvotes: 0

Views: 88

Answers (1)

Tommy
Tommy

Reputation: 100652

The block doesn't reference self, either explicitly or implicitly by referencing an instance variable. So it won't retain self. All it would prima facie retain is the metaclass NSNotificationCenter and what I assume is a global constant, kFetchNewTopicsAndReloadTableData, neither act causing anything else to be retained.

So there's definitely no retain cycle because that block doesn't deal with any transient objects whatsoever.

Even if it did retain self, there'd be no problem. Compare and contrast with something like:

@implementation SomeClass
{
    block_t someHandler;
}

...
    someHandler = [^{ [self doSomething]; } copy];

That creates a retain cycle because the block is then retained by self and self is retained by the block. You may later break the cycle but it's a lot safer to just use a weak reference and not create the cycle in the first place.

As to whether it's bad form to return the block as you do: technically yes on the grounds that you should have copyd it in order to return it. Blocks should be copied if they are to be used beyond the scope in which they are declared. If it were inline you wouldn't need to copy it because that would be the responsibility of dismissViewControllerAnimated:.... That block will get away with it for not capturing anything but global state but that also means the copy would be essentially free so it's not worth making the exception.

As to what you're more likely asking, it's arguably overcomplicating the syntax to add an extra method wrapping the declaration of the block, but if you need the same block several times then the normal rule of factoring would apply.

Upvotes: 1

Related Questions