Making Life Easier
Today I’m here with some useful tips and tricks, nothing ground breaking — just some helpful little tidbits that might make your life a little easier. On the list today:
- The weak reference mambo
- Playing nice with custom controllers and Interface Builder
- The royal self
The Weak Reference Mambo
You should be using weak references absolutely everywhere possible. The problem is, that in order to use weak references for views you have to first declare a strong reference. That is, of course, just a common misconception.
[self.view addSubview: self.weakViewReference = (UIView *)[UIView initWithFrame:CGRectZero]];
Viola, no compiler complaints and it works like a dream — a one liner to let you use weak references for your views.
Playing Nice with Custom Controllers and Interface Builder
You might have run into this; if you redeclare the view property on a UIViewController
subclass and load your custom view in -(void)loadView
you end up clobbering your storyboard/nib view in the process. After all, you don’t want to call [super loadView]
because it’ll load the wrong one!
- (void)loadView { if(self.nibName || self.storyboard) { [super loadView]; } else { self.view = [[TextCircle alloc] init]; } }
Except when it doesn’t — when you’re coming from a storyboard or a nib, you actually want to let the framework do it’s thing. This little snippet of code will let your custom view controllers play nice with interface builder.
The Royal Self
This isn’t really a tip, or a trick, but it’s a knowledge gap that I find all too common in the objective-c world. When you’re working in a class method, self
does exist and it does something useful — it points to the class.
static id sharedInstance; + (id)sharedInstance { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[self alloc] init]; }); return sharedInstance; }
There’s a fully functional, completely generic singleton method thanks to the royal self. It isn’t exactly the most groundbreaking use of this feature — but it’s quick and clear.
That’s all folks
A few quick tips that might save you some time or a headache or two, as promised. And as a bonus, here’s a gist link.