Hacker News new | ask | show | jobs
by pjungwir 4587 days ago
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?