Wednesday, April 27, 2011

iphone interview questions

—- Objective-C related —-
  • identify basic OO concepts and the keywords Objective-C uses (interface, implementation, property, protocol, etc)
  • what is a designated initializer, what is the pattern for the initializers and why ( if (self = [super ...] ) )
  • basic memory management topics, like ownership retain/release/autorelease
    • what happens if you add your just created object to a mutable array, and you release your object
    • what happens if the array is released
    • what happens if you remove the object from the array, and you try to use it
  • trick: garbage collection on iPhone
  • autorelease pool usage
  • property declarations ( assign, nonatomic, readonly, retain, copy )
    • trick: ask about the nonexistent atomic keyword, what does atomic mean
    • ask on how to correctly implement a retaining setter property
    • ask about the circular reference problem and delegates being usually saved with assign rather then retain
  • what is the difference between the dot notation and using the square brackets
    • what happens when we invoke a method on a nil pointer
    • difference between nil and Nil
  • what is KVO and related theory + methods to use when observing
    • does KVO work with ivars too?
  • protocols – maybe: main difference between c#/java interface and protocols
    • what to do in a situation when a class doesn’t implement a method from a protocol
  • what about multiple class inheritance
  • what is fast enumeration
  • class methods vs instance methods
    • visibility of methods
  • what is an actual class in Objective-c (struct)
    • ask about the isa member
    • ask about isKindOfClass isMemberOfClass
  • root classes: NSObject, NSProxy
    • how does proxy-ing work
    • how to fake multiple class inheritance
  • id type
    • what happens during compilation if we invoke a method on an variable with the type id
    • what happens runtime if the method exists
    • what happens if the methods doesn’t exist
    • pro and cons of using the type id
    • what happens here(compile + runtime): NSString *s = [NSNumber numberWithInt:3]; int i = [s intValue];
  • what are class categories and the () category
  • what is an informal protocol
  • what is a delegate, how to create one, and use one
  • what is a selector, how to do a perform selector
    • how to delay executing a selector
    • what to do when the selector has more paramters (NSInvocation>
    • how to start a selector on a background thread
  • how to start a thread
    • what is the first thing to do on a thread (autorelease pool)
    • what is a runloop, and one very common place where it is used (timers, nsurlconnection)
  • how to download something from the internet
    • what is the difference between a synchronous and an asynchronous request
    • small task: explain how to download an image from the internet, and show this in an image view – all this after a button is tapped on the view
  • what are notifications, how to use them
  • what is a memory warning, how do we respond to it
—- A bit more advanced topics —-
  • when to use retainCount (never, and why)
  • why shouldn’t we invoke instance methods in an initializer and the dealloc
  • NSCoding, archiving
  • NSCopying, why can’t we simply use our own objects as key in a dictionary, what to do to solve the problem ( and the difference between a shallow and a deep copy)
—- UIKit related —-
  • what is a view, and a window
  • difference between a view’s bounds and frame
  • what is the resolution of the current available devices, difference between points and pixels (starting with iOS4)
  • what is the responder chain, becomeFirstResponder
  • what do IBOutlet and IBAction mean, what are they preprocessed to
  • how do tableviews function
  • what about multithreading and UIKit
  • what to do when the keyboard appears and hides some parts of the UI that are important
  • why should we release the outlets in viewDidUnload
  • what is awakeFromNib, what is the difference between a nib and a xib
—- CoreData —-
  • what is a context
  • what about multi threading and core data usage
  • what is an NSManagedObjectId – can we save it for later if the application was stopped
  • what types of stores does core data support
  • what is lazy loading, how does this relate to core data, situations when this can be handy
  • how to ready only a few attributes of an entity
  • what is an fetch result controller
  • how to synchronize contexts
  • how could one simulate an NSManagedObject (i’m thinking of the fact that all the properties are dynamic and not synthesized)

Creating custom UITableViewCell Using Interface Builder [UITableView]

Just like user select one row and that row text will be set as product text in next view. Out put of this tutorial will look like this
Picture 11 iPhone Tutorial: {Part 2} Navigatation in UITableView



Picture 12 iPhone Tutorial: {Part 2} Navigatation in UITableView

1. You have to add NavigationController in your application to move from one screen to other. Its really an easy way to navigate from one view to other. So in this tutorial I am going to use UINavigationController. Open ‘SimpleTableAppDelegate.m’ file and change the function ‘applicationDidFinishLaunching’ so that it looks like this:
- (void)applicationDidFinishLaunching:
(UIApplication *)application {
UINavigationController *navController =
[[UINavigationController alloc] initWithRootViewController:viewController];
// Override point for customization after app launch
[window addSubview:navController.view];
[window makeKeyAndVisible];
}
2. Open the SimpleTable code(you can grab it from here). Right click on classes folder in Xcode and select ‘Add > New File…’.

Picture 1 iPhone Tutorial: {Part 2} Navigatation in UITableView

3. Select UIViewController and click Next. Name is ‘NextViewController.m” and press ‘Finish’ button.
Picture 2 iPhone Tutorial: {Part 2} Navigatation in UITableView


Picture 3 iPhone Tutorial: {Part 2} Navigatation in UITableView

4. Open ‘NextViewController.h’ file and write this code after Import and before @end
@interface NextViewController : UIViewController {
IBOutlet UILabel *lblProductTxt;
}

- (IBAction) changeProductText:(NSString *)str;

5. Open NextViewController.m file and write this code before @end
- (IBAction) changeProductText:(NSString *)str{
lblProductTxt.text = str;
}

6. Now last step from xcode is to open ‘SimpleTableViewController.m’ file. Add #import “NextViewController.h” after first import. Write the following code in this method ‘didSelectRowAtIndexPath’ (which was empty)
- (void)tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NextViewController *nextController =
[[NextViewController alloc] initWithNibName:@"NextView"
bundle:nil];
[self.navigationController pushViewController:nextController
animated:YES];
[nextController changeProductText:[arryData
objectAtIndex:indexPath.row]];
}

7. Now open Interface builder and click on ‘File > New..’ and then click again on ‘File > Save’. Name it ‘NextView’ and save this file inside your SimpleTable Project which is in my case in Desktop. It will prompt you to add this file to your project. Click on check box and clicked ‘Add’ button
Picture 4 iPhone Tutorial: {Part 2} Navigatation in UITableView

Picture 5 iPhone Tutorial: {Part 2} Navigatation in UITableView

Picture 6 iPhone Tutorial: {Part 2} Navigatation in UITableView

Picture 7 iPhone Tutorial: {Part 2} Navigatation in UITableView

8. You can see NextView.xib file inside your Xcode project “Group & Files panel under ‘Nib Files’



Picture 8 iPhone Tutorial: {Part 2} Navigatation in UITableView

9. Select File’s Owner in NextView.xib file and press Cmd + 4 to open “Identity Inspector”( Please make sure you select the File’s owner before openning the “Indentity Inspect”). In class write ‘NextViewController’ (Name of the classs). Place two labels on ‘NextView.xib’ file like the picture and map lblProductTxt with ‘txt’ label and map ‘view’ with ‘View’.

Picture 13 iPhone Tutorial: {Part 2} Navigatation in UITableView

Picture 9 iPhone Tutorial: {Part 2} Navigatation in UITableView


Picture 10 iPhone Tutorial: {Part 2} Navigatation in UITableView 

10 To set the title of any view you have to write one line code inside your ‘viewDidLoad’ method (it will be commented in your ViewController classes). So in SimpleTableViewController.m file write (or uncomment viewDidLoad method) following line:
self.title = @"Simple Table Exmaple";

11. Save this project and click on “Build & Go” inside Xcode. You will see a table. Click on any row and you will navigate to another View.
Final output will look like this:

Picture 11 iPhone Tutorial: {Part 2} Navigatation in UITableView

Picture 12 iPhone Tutorial: {Part 2} Navigatation in UITableView

You can grab this code from here.
You can watch the screen cast here.


------------------------- The above post is for Creating UITableview ----------------------

------------------------The following post is for Custom cell -------------------------------

So in this tutorial, i will write only UITableViewCell and link it with UITableView. I will be using above code, which you can grab from here. Final output of this code will be same as part two but to change the design on table will be really simple. You can watch the video tutorial at the end to skip all the text.


Picture 1 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
customize UITableView using UITableViewCell

Steps to follow

Follow these steps to achieve the output like above:
Step 1: Open the SimpleTable project in Xcode (you can grab this code from here. [Note: I am using UITableView part 2 code here]). In Xcode, ‘Group and Panel’ right click on classes, select >Add> New File..>. Now select UITableViewCell and name it ‘TableViewCell’, press finished.

Picture 2 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]


Add UITableViewCell
Picture 3 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]

Select UITableViewCell from wizard

Picture 4 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
Name the UITableViewCell class
Step 2:
Now in ‘TableViewCell.h’ file add following code before @end and after #import:
@interface TableCellView : UITableViewCell {
IBOutlet UILabel *cellText;
}

- (void)setLabelText:(NSString *)_text;
 
Step 3:
Now open ‘TableViewCell.m’ file and write a setter method for label like this:
- (void)setLabelText:(NSString *)_text;{
cellText.text = _text;
}
 
Step 4:
Open SimpleTableViewController.h file and write following:
#import "TableCellView.h"
@interface SimpleTableViewController : UIViewController {
IBOutlet UITableView *tblSimpleTable;
NSArray *arryData;
IBOutlet TableCellView *tblCell;
}
 
Step 5:
Open SimpleTableViewController.h file and import ‘TableCellView.h’ at top.
#import "TableCellView.h"
In cellForRowAtIndexPath method remove all the code or either comment the code. Add the following code in that method:
static NSString *MyIdentifier = @"MyIdentifier";
MyIdentifier = @"tblCellView";

TableCellView *cell = (TableCellView *)
[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if(cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"TableCellView"
owner:self options:nil];
cell = tblCell;
}

[cell setLabelText:[arryData objectAtIndex:indexPath.row]];
return cell;
 
Step 6:
Now open NextView.xib file from your Xcode project. Press cmd + shift + s to save as this file, and give it a name TableViewCell and ‘Add’ to ‘SimpleTable’ project:

Picture 5 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
Save As nib file
  Picture 6 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
Name UITableViewCell xib file

Picture 7 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
Save nib file
Step 7: Now in TableViewCell.xib file, select ‘View’ and then select Edit>Delete (or press ‘back space’ button) to remove the View from xib file

Picture 8 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
Remove View from TableCellView.xib
Picture 9 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
Deleted View from TableCellView

Step 8: Now press cmd + shift + l to open Library. Drag ‘Table View Cell’ to ‘TableViewCell.xib’ file. Select ‘Table View Cell’ and press cmd + 4 and write ‘TableCellView’ in class and press cmd + 1 and write ‘tblCellView’ in Identifier.

Picture 10 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
Add UITableViewCell to nib file
Picture 11 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
Assign Class to Table Cell View

Picture 12 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
Add Identifier to Table Cell View

Step 9: Now select ‘Files Owner’ and press cmd + 4 and type ‘SimpleTableViewController’ in class. Also press cmd + 2 and drag tblCell to ‘Table View Cell’ like in the below picture:
Picture 13 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
Give class name to File’s Owner
Picture 14 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
Map UITableViewCell to Table View Controller
Step 10: Now drag a label inside UITableViewCell and select ‘TableViewCell’, drag cellText with label.
Picture 15 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
Map Label
Step 11: Save the interface builder and your code. Run the application and you will see the output like this:
Picture 16 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
Custom UITableViewCell Output
Looked at bottom pictures to change the color of labels and cell Accessory:
Picture 17 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
Change Table Cell View Accessory


Picture 18 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
Change Label Text colour


Picture 19 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
Label Colour text change

Run the application and you will see the final output.
Picture 1 iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]
Final Output of Custom UITableViewCell

Custom UITableViewCell code

You can grab this code from here.

Now watch me doing it

Tuesday, April 26, 2011

Gyroscope - iPhone

While the entire world was giddily anticipating the start of World Cup soccer this year, it was nose to the grindstone here at Sourcebits developing new soccer madness updates of Funbooth for Mac and iPhone.  Work notwithstanding, our development team had serious fun during production of these applications.  Throughout the beta testing and QA we were constantly capturing images of ourselves in the props of the teams we support, and we made the most of the new social features with the on-the-fly uploading to Facebook and Twitter.  And at the same time, our gaming wing guys at Wandake were busy putting the finishing touches on their now-huge hit Wake Up the Box! for iPhone and iPad.  So it was a real party at times.

While all this was going on, of course there was some big news on June 7, when Steve Jobs introduced yet another Apple engineering marvel: iPhone 4.  Bundled with new features like front-facing camera, superior rear camera, dual mikes for increased noise cancellation, eye-popping Retina Display, multitasking, 720p HD video recording and even a new kind of gyroscope technology, iPhone 4 is a huge evolutionary step in smartphone design.  As the tag line says: “This changes everything.  Again.”  And, marketing hyperbole aside, as far as day-to-day use is concerned for sure this will change the way we use iPhone.
Before this year’s launch, several leaked – or mislaid – iPhone 4 models made the rounds of the major tech blogs, complete with gory dissections and the standard tsunami of specu-babble.  But there was one stealth feature all the teardowns and pundits failed to even guess at: the gyroscope.  And on our side, as veteran iPhone developers, when Steve Jobs announced this during WWDC we were all pretty excited.  And while it still hasn’t gotten much attention in the press, this feature is a game changer in iPhone’s rivalry with Android and Symbian devices.

Apple’s been pioneering smartphone innovations since iPhone’s introduction in 2007 with many widely imitated micro-technologies, in particular the accelerometer.  The accelerometer is a type of sensor that detects changes in a device’s orientation, vibration, rotation or fall by detecting linear acceleration along one of the three X, Y and Z axes – that is: up/down, right/left, and front/back.

3-axis accelerometers enable features we by now take for granted in smartphones (and lately, too, in non-Apple branded consumer digital cameras, music players, and gaming peripherals).  For example, landscape/portrait orientation shifting, tilt for directional control in games and applications, and shake features for refreshing a webpage or shuffling a playlist.  The 1st generation of accelerometer – pre iPhone 4 – could measure only linear motion; it couldn’t sense direction on a compass or twisting motions or rotation, nor had any notion of gravity.

Then last year Apple added a magnetometer to the iPhone 3Gs, enabling it to sense magnetized direction relative to the Earth’s poles. And now, with the introduction of the gyro in iPhone 4, Apple once more ups the ante in spatial detection / orientation with a new sensor for detecting 3-axis angular acceleration around the X,Y and Z axes, enabling far more precise virtualization of pitch, yaw and roll on iPhone.
While detection of change in velocity has been possible for some time thanks to conventional accelerometer calculations in terms of linear acceleration, the gyroscope has been designed to detect angular acceleration, which will detect change in both velocity and direction at the same time.  iPhone 4’s gyroscope enables the sensing of even slight degrees of rotation while simultaneously rejecting linear movements and hand jitters – both still ably handled by accelerometer’s linear movement detection technology.
Combining the 3 axes of the gyroscope along with the 3 axes of the accelerometer now enables iPhone to recognize distance, speed and direction as it moves real-time through space. And thanks to the CoreMotion APIs in iOS, developers with the vision to make use of gyroscope data can access it freely, as some have already done.

3 Excellent Books on iPhone Development

iPhone has been a rage among users ever since it was launched in 2007 and it continues to be the leading mobile device today with millions of applications in the App Store. It has revolutionized mobile computing by giving everybody an opportunity to develop their own applications for the platform. You probably want to develop your own iPhone application, but the question is – Where to begin? There are hundreds of books available on iPhone programming, but not all of them are good enough to give you a quick head-start. In this article, we’ll tell you about three excellent book on iPhone development, which can quickly get you started with iPhone (and even iPad!) application development. 1. Beginning iPhone Development: Exploring the iPhone SDK
This is perhaps the best book for beginners in iPhone development. The book starts with the basics, walking you through the process of downloading and installing Apple’s free iPhone SDK, then stepping you though the creation of your first simple iPhone application. You’ll move on from there, mastering all the iPhone interface elements that you’ve come to know and love, such as buttons, switches, pickers, toolbars, sliders, etc. It will also introduce you to some more advanced topics like GPS API’s and accelerometer. It’s really a must have book for anyone interested in getting started quickly and efficiently with iPhone development. 2. iPhone Programming – The Big Nerd Ranch Guide

This book leads you through essential tools and techniques for developing applications for iPhone, iPad and iPod Touch. You’ll learn about mapping services, accessing accelerometer data, handling multi-touch gestures, ways of sorting and loading data, communication with web services and localization. The book has numerous visual cues and code samples, which will help you get a hang of iPhone programming. It really deserves a place on your bookshelf.
3. Programming in Objective C

The book is not iPhone specific, but it’s still very useful as you need to have a solid foundation in Objective C if you want to develop some really cool iPhone applications. The book assumes no prior programming knowledge and serves as an excellent guide for beginners. You’ll learn about the basics of Objective C programming, Foundation Framework and Cocoa and iPhone SDK.The separation of these main topics, Objective-C Language features and the Foundation Framework for example, almost guarantees that there won’t be much confusion if you are learning the language for the first time and that there will be a distinction between the topics and concepts for each section.

Monday, April 25, 2011

Objective-C Programming in XCode 4 – iPhone iOS 4.3 Hello, World ! tutorial


DemoViewController

1. Install Xcode and create a new project

To develop apps for the iPhone/iPad running iOS, you’ll need a Mac running Mac OS X 10.6.
Apple’s development tools are called Xcode. This tutorial is for Xcode 4, released in March 2011. Please note that you’ll find lots of information on the internet which is valid only for version 3 or 4 of Xcode.
To run your apps on hardware devices, you need to be member in the iOS Developer Program (99$/year). If you are member in the developer program, you can download Xcode 4 for free. If you’re not a member, you can still buy Xcode 4 for $4.99 in the Mac App Store and run your apps in the simulator on the Mac.
So, first step is to download and install Xcode 4 and to run it from /Developer/Applications/Xcode:
Xcode


Choose to create a new project.
Choose iOS > Application > Window-based Application. This is the most simple template for iOS apps. In this tutorial, I intend to show what’s going on and explain all the moving parts in the background. So while there are more suitable templates to build actual apps, please follow along using the bare-boned Window-based Application template.
In this tutorial, I’m going to develop a shopping list app, so if you want to follow along, name your project ‘ShoppingList’. Company Identifier should be a domain name written the other way round. I’m going to use com.example, feel free to use your own domain name. Choose iPhone for Device Family (for the moment, this will be an iPhone-only app) and uncheck Use Core Data (a database framework, we don’t need this right now) and uncheck Include Unit Tests (we will do unit tests only in a later chapter):
Creating a new iPhone project
We now have a new iPhone project.

2. Run the app

Simulator

Check that the iPhone simulator is checked for Scheme and hit Run (⌘R):
Running in the simulator
The empty app should be running in the simulator now:
iPhone Simulator

Device

To run the app on the device, you need to be iOS Developer Program member.
Connect the iPhone to your Mac. Open the Organizer in Xcode via Window > Organizer and choose the device. The first time you might have to enable it for development.
Click the Add to Portal button. It will query for your Apple account password and offer to request a certificate for you. If it asks to wait for your Provisioning Profile to be created, refresh the Provisioning Profiles section until a valid "Team Provisioning Profile: *" pops up there. The icon besides the device should be green by now:
Xcode Organizer
Add to Portal does many things automatically:
  • It creates a developer certificate for you. This includes a public/private keypair which is added to your OS X keychain. iPhone apps need to signed to run on the device and your key will be used to sign your app.
  • It uploads a request to sign the certificate to the Apple iOS Provisioning Portal. Your certificate needs to be signed by Apple, otherwise the app will not run on the device.
  • It adds the Unique Device ID (UDID) of your device to the iOS Provisioning Portal.
  • It creates an App ID in the iOS Provisioning Portal.
  • It creates a Provisioning Profile in the iOS Provisioning Portal. This is the permission to run apps (having a matching App ID) signed with your key on only the devices with the specified UDIDs.
  • It downloads the provisioning profile from the iOS Provisioning Portal and installs it to Xcode and on your phone (you can check that on the phone using Prefs > General > Profiles).
Provisioning Profile
You can now pick the hardware device in the Scheme selector and run the app on the hardware device:
Running in the simulator






App running on the device

3. Use the documentation

Let’s have a look at how the startup of an iPhone app works. The entry point is the main.m file in your project:
main.m
This does some basic setup:
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
Important here is the UIApplicationMain call which initializes the app. To learn more about UIApplicationMain (or about anything), have a look at the documentation. Go to Xcode > Preferences > Documentation and click GET for the iOS Library. This will download all the available documentation:
Download iOS Library Documentation
After it finishes downloading, select UIApplicationMain in the source code file and click Help > Search Documentation for Selected Text:
UIApplicationMain documentation
Hint: Configure a convenient key binding for Help > Search Documentation for Selected Text in Xcode > Preferences > Key Bindings:
Hotkey for documentation

4. Add a UINavigationController

After we have learned how to use the Xcode documentation in part 3 of the iPhone tutorial, let’s add a navigation controller that provides the typical navigation bar that will host the navigation controls like the back button:
Navigation Controller
But before that, some more basics. We have seen the call to UIApplicationMain() in main.m:
int retVal = UIApplicationMain(argc, argv, nil, nil);
From the documentation one can learn that there is an application delegate object which takes control as soon as the application is started. UIApplicationMain loads this object from the application's main nib file by default. Let’s have a look at how this works.
NIB files are created by the graphical user interface editor of Xcode. They have the file extension .xib:
MainWindow.xib
NIB/XIB files contain "pickled" objects. Our .xib file contains two objects, an App Delegate and a Window:
Inspect MainWindow.xib
When the app starts, the .xib file is loaded by UIApplicationMain and all the objects come to life. Let’s have a look at the App Delegate. If you inspect this object, you can see that this object is created from one of our project classes:
How the app delegate is loaded
If you have a look the ShoppingListAppDelegate.m implementation, you’ll see that this class makes the window visible:
- (BOOL)application:(UIApplication *)app didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self.window makeKeyAndVisible];
return YES;
}
This is the Window object which is loaded from our .xib file. We will have a deeper look in the connection between classes and objects from .xib files in a later part of the tutorial after we went through some basics of the Objective C language.
So now we know: Our application delegate is loaded from our .xib file and makes the Window from the .xib file visible. Let’s play around with the window a bit. For example, change the background color:
Change the window background color in the NIB
If you run the app now, you will see the Window with the changed background color.
You can add UI objects by dragging them from the Object Library:
Adding a control in interface builder
Let’s see if we can add a UINavigationController the same way. If you try it, you will learn that you cannot drag the navigation controller on the Window. This is because a navigation controller is not a view itself, so it cannot be added to a Window. A Controller contains and manages a View, but it is not a view itself. But we can add it besides the Window as separate object:
Adding a UINavigationController in interface builder
The important point here is: where is the connection between the Window that will be on the screen and the Navigation Controller? Currently there is none, we just added another object which will not be used. We have to establish a connection by telling our Window object that it should use our navigation controller. This is done by setting the property rootViewController on the Window object:
Set the NavigationController as rootViewController for the Window
If you run the app now, you’ll see that the view controller is used by the Window:
Window with NavigationController

5. Add a UIViewController

After we have added a navigation controller in part 4 of the iPhone tutorial, we can now begin to add Views to the app. Views are the screens of the app. A View is usually accompanied by a ViewController which is responsible to manage the View and all the action that is supposed to go on, like reacting on user events.
The UINavigationController that we added in the last part is responsible for managing all the ViewControllers of our app. Because of this, we shouldn’t add anything to the Window directly. Everything we want to show goes into the UINavigationController. So, whenever we want to add a new screen to the app, we add a UIViewController to the UINavigationController. The root view controller (the one which is displayed initially) and its View can be added conveniently in Interface Builder:
Add a view controller
Also add a Slider, Label and Rounded Rect Button to the View and set a title for the ViewController so we have some controls to experiment with later on:
Add View Controls
So by now, if you run the app, you should see the controls you just added inside the View which is managed by the ViewController which is managed by the UINavigationController:
App with some controls
Now, let’s add a some behaviour to our new view. This is the point where we need to start to work with the programming language Objective C.
In this tutorial, I’ll take a chance to try to explain everything to the point where somebody who never did any programming before has a chance to follow. If you already know other programming languages, skip the (for non-programmers) sections and read the (for programmers) sections instead (and vice-versa).

A brief introduction to Objective C Objects (for non-programmers)

We have already seen ‘Objects’ and created them using Interface Builder. Things like Buttons, Labels, Windows, View Controllers, all these are objects. When we drag two Buttons into Interface Builder and run the app, we see two Button objects in action. You can work with objects using two ways. They can have attributes (also called properties) that can be changed. We can do this in Interface Builder or later in our program when the app is running. Have a look at the properties of the Label object in Interface Builder to get an idea what properties you can manipulate:
Label attributes
The other thing we can do with objects is to talk to them by sending them messages. For example, in a later part of the tutorial, we will go to our UINavigationController object and ask it to show some other view.
So, objects have attributes which we can manipulate and we can talk to them by sending messages. Now, you might wonder, where does the definition come from what attributes we can manipulate and what messages we can send? Here is the trick: Every object has some kind of a blueprint which defines these things. This is called a class. A class like UIButton defines attributes and messages. When you create a button, your button object is created using this UIButton blueprint. Now, many classes like UIButton or UIViewController were written by the Apple engineers and we have just to use them like we already did. But sometimes we have to create new classes ourselves. And here is another neat trick: We can not only create completely new classes, we also can take an existing class and add our own parts on top (this is called to create a subclass).
This is what we will do right now. We have this UIViewController object in our app which is responsible to handle all the action in our View. The class UIViewController has lots of attributes we can change and messages we can send. But UIViewController objects also get messages sent to it and we can add extra behaviour by creating our own variant of the class and reacting on such messages.

A brief introduction to Objective C Objects (for programmers)

Objective C has a very dynamic object model, you can for example call methods reflectively or add methods dynamically at runtime. Because of this, I’ll use the term “to send a message” instead of “to call a method”. We will see all the details, like the syntax for defining classes and sending messages, in later parts of the tutorial. In the meantime, check out the The Objective-C Programming Language.

Adding behaviour to a View Controller by creating a UIViewController subclass

Now, let’s say we want our ViewController to do something. Currently nothing happens at all, it is just there, managing our View with the Slider, Button and Label in it. We have this UIViewController object in our .xib and if you look closely, you can see that it is created from the class UIViewController:
Classes in Interface Builder
Lets create a UIViewController subclass so that we can add our own behavior. To do this, right-click the ShoppingList folder and create a new File:
Create a new file
Choose UIViewController subclass:
Create a UIViewController subclass
Choose to create a subclass of UIViewController and uncheck With XIB for user interface (we want to connect it to our existing XIB instead of creating another XIB file):
Create a UIViewController subclass
Name it anything you want, for example DemoViewController.m:
UIViewController file name
We now have two new files in our project: DemoViewController.h and DemoViewController.m. We will have a look at all the code in these files in great detail in a later part of the tutorial.
For now, let’s just writing some text out to the console when the view is loaded so we can see something happening. Scroll down in the DemoViewController.m file looking for viewDidLoad. viewDidLoad is a message which is sent to objects of our class whenever the view just came to life:
Add a NSLog(@"DemoViewController says hello"); statement to log a message to the console:
DemoViewController
Now, one last step is necessary for this to work. We need to change our XIB so that it doesn’t create a regular UIViewController object but a DemoViewController:
Change View Controller class in XIB
Now run the app and check the console for the message:
Console message