Last active
December 26, 2015 09:29
-
-
Save andrewsardone/7130116 to your computer and use it in GitHub Desktop.
Using a compound statement enclosed in parentheses to enclose scope of a local UIView that's added to your view controller's view hierarchy and held as a weak reference. In response to http://ashfurrow.com/blog/weakstrong-dance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "ViewController.h" | |
@interface ViewController () | |
@property (nonatomic, weak) UILabel *label; | |
@end | |
@implementation ViewController | |
- (void)viewDidLoad | |
{ | |
[super viewDidLoad]; | |
// For more information on GNU C's statement expressions (and conveniently, Clang's | |
// statement expressions, too), see http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html | |
// and http://cocoa-dom.tumblr.com/post/56517731293/new-thing-i-do-in-code | |
// `label`, being the last expression, becomes the value of the entire | |
// statement expression, that is, the value of everything between ({}) to | |
// outsiders. So, you could *kind of* think about it like you're passing the | |
// return value of some anonymous function to -[UIView addSubview:]. | |
[self.view addSubview:({ | |
UILabel *label = [UILabel new]; | |
label.text = @"Hello world"; | |
label.frame = (CGRect) { .origin.x = 20, .origin.y = 100 }; | |
[label sizeToFit]; | |
self.label = label; | |
})]; | |
// Alternatively, if you don't like the GNU C extension nature of statement | |
// expressions, you could create an anonymous block and immediately evaluate | |
// it. | |
[self.view addSubview:^id{ | |
UILabel *label = [UILabel new]; | |
label.text = @"Hello world"; | |
label.frame = (CGRect) { .origin.x = 20, .origin.y = 100 }; | |
[label sizeToFit]; | |
self.label = label; | |
return self.label; | |
}()]; | |
// `label` is not polluting the local scope of -viewDidLoad, and | |
// `self.label` is a weak reference. | |
// In response to http://ashfurrow.com/blog/weakstrong-dance | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment