Clicky

iOS Dev Nugget 197 App Initialization Code

.

Need to run a code review on your codebase? Hire me

Sometimes you want to set global state before any of your other code runs. With Obj-C, you can override the +load method for a class to do that. The +load method runs once-only, automatically when the class is loaded at launch.

If you try to override the class load() function in Swift, you will get the error "Method 'load()' defines Objective-C class method 'load', which is not permitted by Swift". So you have to fall back to overriding the class function initialize() instead. There is a key difference between load() and initialize(). The former basically runs when the app starts up (when the class is loaded), but the latter only when the class is first used, so you might want to implement initialize() for your class which implements UIApplicationDelegate.

Either way, you should be careful not to put long running code in load() or initialize() because that will block the main thread and the launch of your app.


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues