This is a transcript of an audio podcast.
Hi. I'm Kirby Turner. I'm the author of the book Learning iPad Programming: A Hands-on Guide to Building iPad Apps with iOS 5. In this episode, I'm gonna share some tips about writing a universal app.
A universal app is an app that runs natively both on the iPad and on the iPhone. This can be a great benefit to the users of the app, because they only have to buy one app, and it can run on all their devices.
But this comes at a cost to you, the developer, because in a sense you're writing two separate apps: an iPhone app and an iPad app, and packaging it up as one single app. This can make your code a little bit more cumbersome to write, because you have to maintain knowledge within your code as to whether you're working on an iPad or an iPhone. There are some conventions that you can follow that can make life a little bit easier for you. The first is to name your resources, such as your XIB files, with a tilde (~) followed by ipad or iphone (~ipad or ~iphone). By doing this, [you let the device] determine which is the correct NIB to load.
So, for example, let's say that I have a RootViewController, and the RootViewController is gonna load the XIB file rootview. If you have two XIB files, RootView~ipad.xib and RootView~iphone.xib, iOS will load the appropriate device-specific version of the XIB file for you. So you don't have to include checks within your code.
There are other situations where you're gonna have to include checks within your code, and when you do that, you'll want to use the C macro UI_USER_INTERFACE_IDIOM. That macro will tell you whether you're running on an iPad or an iPhone device.
The last little tip I'll share when writing universal apps is that, when you're using UI_USER_INTERFACE_IDIOM within your application, you'll find that you have a number of IF statements scattered throughout your ViewControllers, constantly checking
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) //do this
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) //do that
This can lead to bloated code and make it harder to maintain your code. A better approach is to subclass your ViewController to device-specific versions. Again, using the RootViewController as an example, you would create a base-class RootViewController as your base class; your shared code that is device-independent would go inside that ViewController. You would then derive two additional ViewControllers. You would have a RootViewController_iPad and RootViewController_iPhone. Within those derived classes, you would include iPhone- and iPad-specific code.
This will help you eliminate the UI_USER_INTERFACE_IDIOM check throughout your code.
For more information, visit onpodcastweekly.com and subscribe to all our podcasts. Brought to you by the publishing imprints and information portal of Pearson Education.