Skip to content

Comment on NSNotificationCenter with blocks considered harmful

Comments

The book Programming iOS 6 by Matt Neuburg recommends the "weak-strong dance" for this, like so (p. 326):

    __weak MyClass* wself = self;
    self->observer = [[NSNotificationCenter defaultCenter]
                       addObserverForName:@"heyho"
                       object:nil queue:nil
                       usingBlock:^(NSNotification *n) {
                         MyClass *sself = wself;
                         if (sself) {
                           NSLog(@"%@", sself);
                         }
                       }];
Do other people agree this fixes the problem?

Also, it's my understanding closures only cause retain cycles if the method taking the block copies the block, per the docs: "When a block is copied, it creates strong references to object variables used within the block." Therefore this dance is not necessary for e.g. [NSURLConnection sendAsynchronousRequest:queue:completionHandler:]. Is that correct?

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.