AppDelegate is Not The First Code to Run

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

Lukas Thoms
Jun 10, 2016 · 2 min read

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.

Image for post
Image for post

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.

Image for post
Image for post
Image for post
Image for post

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.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store