AppDelegate is Not The First Code to Run

This one weird trick executes code earlier than you‘d expect.

Hello fellow iOS engineers. I’ll be quick.

In Apple’s own doc, The App Life Cycle, they declare that the method application:willFinishLaunchingWithOptions: is “your app’s first chance to execute code at launch time.”

Indeed, most developers, including myself, learn that the AppDelegate is the first place code is executed, and therefore a great place to do any initial setup for your app.

If you’re using Swift with storyboards, that is incorrect.

A simplified AppDelegate

Turns out that if your initial view controller is in a Storyboard, written in Swift, and instantiates its properties’ data when they’re declared, the code for said instantiation runs before everything else.

A barebones initial view controller with a single property
The struct used to intiantiate the data.

If we run this fun little useless app, the output looks like this:

Hello from ViewController property
Hello from willFinishLaunchingWithOptions
Hello from didFinishLaunchingWithOptions
Hello from viewDidLoad

None of this information really changes anything about how we should design apps. As a matter of convention, AppDelegate is still the best place for us all to run our initial code, considering that most apps aren’t built with Swift and storyboards (yet).

Nor is it really that interesting that code can be run before AppDelegate — I’m sure if you wanted to be clever you could find myraid ways to run code before willFinishLaunchingWithOptions:, like fiddling with the main function.

But it’s an unexpected order of operations caused by what I would consider a non-edge case for writing code with storyboards, and something I figured worth knowing for those developers who are. Personally, it caused me a slight headache earlier today when the code for a property was causing my app to crash, because it relied on something in AppDelegate running before it.

If, for some reason, you’d like to try this out yourself, the code is available on GitHub.

So there ya have it. Just some little trivia to keep in mind. Happy coding.

A single golf clap? Or a long standing ovation?

By clapping more or less, you can signal to us which stories really stand out.