There are two things that I have recently grown to love when it comes to writing iOS code and those are Protocols and Delegates. If you written anything with a UITableView in it , then you’ve used Protocols before. For instance, cellForRowAtIndexPath is in fact a method that is defined in the UITableViewDataSource protocol. You’ve been using protocols this whole time and didn’t even know it, or maybe you did. So how do you make your own Protocol and Delegates? It’s actually fairly boilerplate and super simple. Here is a simple example.
@protocol MyClassDelegate <NSObject>
// Required means if they want to use the delegate they
// have to implement it.
@interface MyClass : NSObject
// We don’t know what kind of class is going to adopt us at
//compile time, that’s why this is an id
@property (nonatomic, assign) id delegate;
If you’re curious as to why you see the assign property here check this great post on StackOverflow
// Be sure to synthesize your instance variable
// Method used to call to our delegate and let it do the work.
// Sanity check, did they set the delegate?
if([self delegate] != nil)
[[self delegate] taskComplete:YES];
// Do some task like let a timer run and call our method when done.
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(taskComplete) userInfo:nil repeats:YES];
Ok, the majority of the boilerplate is out of the way and we just need to write something that will actually adopt our protocol. The adopter will be the one who called MyClass to do some task and will be expecting MyClass to let it know when it’s done. This is why protocols are so great. Suppose you have a rather complex project and don’t want to create lots of bidirectional linkages between your classes, in that case delegation like this is going to be your best friend. It’s like having function pointers ad callbacks, but the communication goes both ways easily. Time to adopt our protocol and actually use it in a class.
/* MyDelegateAdopter.h */
// Only reason I’m using a UIViewController is to have a place to set
// the delegate. This could be any class.
@interface MyDelegateAdopter : UIViewController
/* MyDelegateAdopter.m */
myClass = [[MyClass alloc] init];
// Very important. If we don’t let myClass know who the delegate
// is we’ll never get the protocol methods called to us.
// Delegate Method, this will get called when [myClass doSomeTask]
Well, that’s about it. Pretty easy to setup, but great tool to have. Once you get used to using them in your own codebase you’ll wonder how you lived without leveraging them. If you want to read more check out cocoanetics for some info on delegate messaging in iOS with respect to the background task switching.