4 ms·
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
by pjungwir 13y 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?
- ddustin 13y agoThis is the correct way to access ivars. Though it makes a lot of indents so I usually do a return. I also use __strong to be explicit to the reader. __strong MyClass *strongSelf = weakSelf; if(!strongSelf) return; ... Rest of block It's also worth noting calling functions on weakSelf can in turn access ivars. Getting a strong reference to self solves both the issues. NSLog calls [self description] in your example.
- deleted 13y ago[deleted]