Skip to content

Instantly share code, notes, and snippets.

@andrewsardone
Last active December 26, 2015 09:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewsardone/7130116 to your computer and use it in GitHub Desktop.
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
#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