Slides and Sample Code from my 360|iDev Talks

I’ve had the pleasure of speaking at this year’s 360|iDev conference, which so far has been an amazing conference. Here are my slides and sample code:

Developing for Apple Watch With Swift:
Sample Code:

Advanced Dates and Times in Swift:
Sample Code (Swift Playgrounds):
Sample Code (iOS App):


Understanding Delegation

I’ve seen a lot of people learning iOS for the first time. Some of them have been learning Objective-C as their first programming language. Understanding delegation is without fail a stumbling block as you learn the language and the frameworks. This blog post is going to attempt to explain delegation using what I have come up with as my best analogy for it so far. I call this analogy “the Shirt Delegate.”

While not many people can relate directly to the fantastically rich, we can imagine the things we would want in our life if, say, Google bought our app for a cool billion. You might want fancy cars or a new Mac Pro, but you know what I want? A Shirt Delegate.

When fantastically-rich Jeff goes to bed at night, I take off my shirt and put it in a bin. When I wake up, the shirt is gone and a new one is hanging in my closet, pressed and ready to wear. I don’t know how it got there, and I don’t care. All I know is this:

  • When I took my shirt off, I handed it to my delegate (in this case, using the bin in my closet)
  • In the morning, when I needed a shirt, it was provided by the delegate

I don’t need to know my shirt delegate’s name, or really even anything about him or her. Heck, I don’t even need to know if my shirt delegate is human. All I care about as far as he or she is concerned is the shirt situation.

Delegates, you see, are a lot like this. A given delegate is there to respond to its master’s whims. Consider a table view delegate. It knows someone tapped on a cell, so it calls its delegate’s ‑tableView:didSelectRowAtIndexPath: method—and that’s the extent of what it knows about what the delegate is going to do with that information.

Our shirt delegate, then, might have two methods:

@protocol ShirtDelegate

– (void)personDidRemoveShirt:(Shirt *)aShirt;
– (Shirt *)shirtForToday;


Only the important information is included in each.

Consider the application delegate. The application starts up, and let’s say it has a push notification the user tapped to invoke it, so it has something in the launchOptions dictionary. The application reads the value passed in to UIApplicationMain() in the main.m file to find out the kind of delegate it needs, creates one, and hands over the launchOptions dictionary to it. In this case the application does know a little bit about the delegate—enough to create one, anyway. But it doesn’t need to know anything about the launchOptions dictionary or anything about what happens in ‑application:didFinishLaunchingWithOptions:.

The purpose of delegation is simple: to decouple your code. The more knowledge a class has about other classes, the more coupling there is in your code. Like a spiderweb sticking to everything, this coupling makes it harder to change individual portions of your app, harder to migrate your apps to new platforms, and is just generally messy. Bringing it back to our original analogy: the fantastically rich are too busy worried about their fleet of supercars, their investment portfolio, and the design of the foyer in their third home; they don’t care about what brand of detergent the shirt delegate uses.

CocoaConf Columbus 2012 Slides and Code

Yesterday I gave a talk on concurrency in OS X and iOS at CocoaConf Columbus. As promised, here are the slides and code:


Fun With the Objective-C Runtime: Run Code at Deallocation of Any Object

Update: This post is getting some attention lately, so I’ve updated it a bit to be less incorrect.

Sometimes when you’re debugging an application, especially one that you’ve inherited, you find yourself wondering when an object is released. Autorelease pools only compound the problem, delaying the actual release until the run loop is idle. In this post, I’ll show you how to take advantage of new features in the Objective-C runtime to run arbitrary code when any object—whether it’s your own or a part of Apple’s frameworks—is deallocated.

We’ll be taking advantage of the Objective-C runtime’s new associated objects behavior. When you associate an object with another object using retain or copy semantics, the runtime automatically handles releasing it at the appropriate time. So, if we want one object to be released when another object is deallocated, we simply associate them:

id objectToBeDeallocated;
id objectWeWantToBeReleasedWhenThatHappens;


Now, when objectToBeDeallocated is deallocated, objectWeWantToBeReleasedWhenThatHappens will be sent a -release message automatically. The association policy passed as the last parameter to the function can be one of the following:

OBJC_ASSOCIATION_ASSIGN No memory management; the value is simply assigned.
OBJC_ASSOCIATION_RETAIN_NONATOMIC Retains the object non-atomically.
OBJC_ASSOCIATION_COPY_NONATOMIC Copies the object non-atomically.
OBJC_ASSOCIATION_RETAIN Retains the object atomically.
OBJC_ASSOCIATION_COPY Copies the object atomically.

Obviously, using OBJC_ASSOCIATION_ASSIGN won’t work for us, since it won’t cause the object to be retained. We also don’t want to use either of the copy policies, since we only want one copy of our objects around. For this example I’ll be using OBJC_ASSOCIATION_RETAIN, but not over OBJC_ASSOCIATION_RETAIN_NONATOMIC for any compelling reason.

Now that we know how to release an object when another is deallocated, we need to create an object to run arbitrary code at deallocation time. Blocks are an excellent tool for this, so I created a dead-simple class, JKBlockExecutor, to handle the running of the block:

typedef void (^voidBlock)(void);

@interface JKBlockExecutor : NSObject {
	voidBlock	block;

@property (nonatomic, readwrite, copy) voidBlock	block;

- (id)initWithBlock:(voidBlock)block;


@implementation JKBlockExecutor

@synthesize block;

- (id)initWithBlock:(voidBlock)aBlock
	self = [super init];

	if (self) {
		block = Block_copy(aBlock);

	return self;

- (void)dealloc
	if (block != nil) {

	[super dealloc];


Now that we can pass arbitrary code to a JKBlockExecutor (and if you have a better name I’m all ears), we can make a category on NSObject to make the association for us:

const void *runAtDeallocBlockKey = &runAtDeallocBlockKey;

@interface NSObject (JK_RunAtDealloc)

- (void)runAtDealloc:(voidBlock)block;


@implementation NSObject (JK_RunAtDealloc)

- (void)runAtDealloc:(voidBlock)block
	if (block) {
		JKBlockExecutor *executor = [[JKBlockExecutor alloc] initWithBlock:block];


		[executor release];


So, how do you use it? The following example prints “Deallocating foo!” when foo is deallocated:

NSObject *foo = [[NSObject alloc] init];

[foo runAtDealloc:^{
	NSLog(@"Deallocating foo!");

[foo release];

And that’s all there is to it!

Well, almost. There is one gotcha that I must warn you about: don’t access the object from within the block. There are two reasons. First, I’m not sure where in the deallocation process the Objective-C runtime releases its associated objects, so accessing the object may result in a crash. Second, if you reference the object from within the block, the block will retain the object. This causes a retain cycle where the block and the object each own each other, so neither will ever be released. If you absolutely must reference your object (at your own risk), then do it like so:

NSObject *foo = [[NSObject alloc] init];

__block id objectRef = foo;

[foo runAtDealloc:^{
	NSLog(@"Deallocating foo at address %p!", objectRef);

[foo release];

Using the __block storage qualifier on an Objective-C object causes the runtime to avoid retaining the object, since the dymanics of object retain counts inside of blocks would be far too hairy to manage automatically. Seriously, though: don’t do it unless you absolutely must.

So there you have it: a quick and dirty category on NSObject to run arbitrary code at deallocation. I don’t really see a use it for it in production code, but on those occasions when you’re debugging someone else’s memory management, this could be handy. Since it uses blocks and associated objects, you’ll need to be running Mac OS X Snow Leopard (64-bit) or later or iOS 4.0 or later.