iPhone Application Development – MVC and Programming Basics

Kanya Srinisavan
This entry is part 2 of 10 in the series iPhone Application Development

iPhone Application Development

In my previous article, we learned some of the basic concepts in iOS application development. In this tutorial we will try to understand the iOS design pattern and some basic concepts.

Design Pattern

iOS applications follows the MVC design pattern.

  • Model: Represents the business logic of your application
  • View: Represents what the user sees in the device
  • Controller: Acts as a mediator between the Model and View. There should not be any direct conversation between the View and the Model. The Controller updates the View based on any changes in the underlying Model. If the user enters or updates any information in the View, the changes are reflected in the Model with the help of the Controller.

We will not have a single Controller to manage all the Models and the Views as it adds complexity to the application. So we will have multiple MVCs in an application that will interact with each other and address the purpose of the application.

How does a View or Model interact with the Controller?

Views can interact with the Controller with the help of targets or delegates.

Whenever the user interacts with a View, for example by touching a button, the View can set the Controller associated with it as the target of the user’s action. Thus the Controller can decide on further actions to be taken. We will see how this can be achieved in the later part of this tutorial.

Views can also delegate some of the actions to the Controller by setting the Controller as its delegate.

For example, in case of a text field, a decision on what should happen when the user starts typing in the text field or when the user has finished typing in the text field could be left to the Controller. This could be accomplished by setting the Controller as the textfield’s delegate.

We can also make the Controllers listen for changes in the underlying Model. The Model can then broadcast the changes to all the listening Controllers through notifications.

Development Fundamentals

We will set the wheels in motion by examinining the basic building blocks of iOS programming – Interface and Implementation files.

Interface File

The Interface or Header file contains declarations of all public instance variables and methods.

Sample:

#import <Foundation/Foundation.h>
@interface Sample:NSObject
//variable and method declaration goes here
@property (nonatomic,strong) NSString *strName;
-(void) printToConsole:(NSString *) strLog;
@end

Points to note:

  • The file starts with the keyword @interface followed by the class name Sample.
  • NSObject denotes the superclass of the Sample class. NSObject is the base class for all the Objective C classes.
  • The class defined and its super class are separated by a colon indicating the inheritance concept. Remember there is no multiple inheritance in Objective C.
  • The #import statement specifies the libraries that are to be included. The Foundation framework contains classes and functions for both iOS and OSX development. NSObject, NSString, NSArray, and NSDictionary are all part of the Foundation framework.
  • When we define a View or a View Controller class, we will import the UIKIT framework which contains classes and functions necessary for iOS development. These classes will be the subclass of UIView or UIViewController available in the UIKIT framework. We have a similar framework called Appkit framework for Mac Application development.
  • @property declares the getter and setter methods of the variable strName. The actual getter and setter methods are not visible in the code, but it all happens behind the scene. We can override the getter and setter methods if required in the implementation file.
  • nonatomic,strong denotes the property attributes on which the getter and setter methods are generated. It influences the way the object’s memory is managed. We will see this in detail in my future tutorials.
  • - (void) printToConsole:(NSString *) strLog; denotes the method declaration.
    1. - indicates that it is an instance method. + would denote a static method.
    2. void is the return type.
    3. printToConsole is the name of the function.
    4. strLog is the argument. Arguments appear generally after the colon.
    5. General Syntax:
      • (Return Type) methodName:(arg1 Type)arg1:(arg2 Type)arg2;
      • (Return type) methodName:(arg1 Type)arg1 methodName:(arg2 Type)arg2

Implementation File

Sample:

@interface Sample()

//Private variables and methods declared here
@end
@implementation Sample
@synthesize strName
//Method Definitions
- (void) printToConsole:(NSStsring *) strLog
{	
NSLog(@”Understanding the basics is important”)
NSLog(@”Logs ”+ strLog)
}
@end

Points to note:

  • All Private methods and variables can be declared under the interface section in the implementation file.
  • Starts with the keyword @implementation.
  • @synthesize represents the variable’s getter and setter method definitions.
  • The methods declared in the .h file are implemented in the .m file. In our sample printToConsole method’s implementation is done in this file. The NSLog function helps in printing logs to the console. String values are always prefixed with a @ symbol. NSLog could be helpful for debugging your application.
  • Both the .h and .m files should end with the keyword @end.

Create a Sample App

Now, let’s create a simple app to find out how the interaction between a View and its Controller happens.

So, create a Single view application as I explained in my previous article.

Click on the TTTViewcontroller.xib and select the File owner and then select the Identity Inspector. The class mentioned here is responsible for all the actions that happen inside this View.

view controller

Drag a button from the objects library and place it inside the View.

drag the object

TTViewController

Change the button’s title to Click me.

click me

We can create a reference to this button in the TTTViewController. In iOS terms, we call this as an outlet. An IBOutlet variable in the controller represents some UI element in the Interface Builder.

To create an outlet, select the Assistant Editor on the toolbar. Place your TTTViewController.Xib on one side and TTTViewController.h on the other side.

Now right click on the button and point to New Referencing Outlet in the dropdown and drag it to the .h file as shown below.

assistant editor

Give the variable a name in the popover and select connect.

name and connect

Now your interface file will have an IBOutlet variable auto generated as shown below.

#import <UIKit/UIKit.h>
@interface TTTViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIButton *btnClickMe;
@end

We can also specify the action that should be invoked on the touch of a button.

Right click on the button and select the circle and drag a connection from the Touch Up Inside event of the button to the controller file as shown below.

touch up inside

Enter the method name and select connect.

connect

Now your interface file will change as shown below.

@interface TTTViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIButton *btnClickMe;- (IBAction)btnClickAction:(id)sender;
@end

Points to note:

  • IBAction means that this method will be invoked on some action in the View.
  • IBAction denotes a void return value.
  • sender argument in the method denotes the reference to the button that is clicked.
  • id is the generic data type for all Objective C classes.
  • An empty method definition will also be auto generated in the implementation file.
  • Thus, the View interacts with the Controller by setting the target action that should be invoked in the Controller when the user interacts with the View.

We will define the method in the implementation file as given below.

- (IBAction)btnClickAction:(id)sender {    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Hi" message:@"Button clicked!!!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];
}

Note the way an alert View is created. Select alt and click on UIAlertview to get more information on alert View.

Run the application in the simulator.

simulator

Conclusion

By the end of this article you should understand how XCode has simplified programming to a large extent.

We’ll explore some more interesting concepts in my future articles.

iPhone Application Development

<< iPhone Application Development – Getting StartediPhone Application Development – View Controllers >>

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Anonymous

    The image in the “Create a Sample App” section is broken. just saying ! Good post anyway.