Wednesday, 12 June 2013

Constructors and Creating Objects in Objective C

Hi, how are you doing guys.... I am back... I hope you guys got some familiarity with the Objective C syntax we discussed in one of my last tutorial. In this tutorial we will learn about how we write constructors/initializers and how to create an object in Objective C.

Lets start.... constructor/initializer is a method which we call while creating a new object in Object Oriented Programming. In this method we write all the code related to initial setup of an object. Objective C have a default construction called init which is present in its root class NSObject. We can override default initializer. It looks like below :

Default Initializer


- (id)init
{
    if( self = [super init] )
    {
        // Initialize your object here
    }
    
    return self;
}

Confused!!!! Lets go one by one line. 

1. - (id)init

- represents it is a class method. id is generic type. It can hold any kind of object. We will see more about id in our next tutorials. init is the initializer name.

2. ifself = [super init] )

self represents current instance/object. [super init] will call the super class initializer.

3. return self;

Finally it returns the properly initialized object.

Custom Initializer 

Okay, now lets create a custom constructor. We will take the same Employee class earlier and will try to initialize his firstName, lastName and salary. Here is the code for it :

Interface 


@interface Employee : NSObject
{
    NSString *firstName;
    NSString *lastName;
    float salary;
}

- (id)initWithFirstName:(NSString *)aFirstName
               lastName:(NSString *)aLastName
                 salary:(float)aSalary;

@end

Implementation 


#import "Employee.h"

@implementation Employee

- (id)initWithFirstName:(NSString *)aFirstName
               lastName:(NSString *)aLastName
                 salary:(float)aSalary
{
    if( self = [super init] )
    {
        firstName = aFirstName;
        lastName = aLastName;
        salary = aSalary;
    }
    
    return self;
}

@end

Above code explains how a class Employee with properties firstName, lastName and salary and a constructor looks like. Now, lets create an object of type Employee....

Object Creation

Option 1:

// Using Default Initializer
Employee *employeeWithDefaultInit = [[Employee alloc] init];
        
// Using Custom Initializer
Employee *employeeWithCustomInit = [[Employee alloc] initWithFirstName:@"Naga" lastName:@"Malleswar" salary:5000];

In the above code I have associated two method calls in single statement. We can make them two separate statements like below, but followed convention is Option 1.

Option 2:

// Using Default Initializer
Employee *employeeWithDefaultInit = [Employee alloc];
employeeWithDefaultInit = [employeeWithDefaultInit init];
        
// Using Custom Initializer
Employee *employeeWithCustomInit = [Employee alloc];
employeeWithCustomInit = [employeeWithCustomInit initWithFirstName:@"Naga" lastName:@"Malleswar" salary:5000];

Both the above options are same. Only thing is convention. Most of the programmers follow Option 1 to create objects. One may get a doubt. What is alloc is??? alloc is a method to allocate memory. Object creation completes only if we send both alloc and init messages to a new object.

Thanks for your time guys. In our next tutorial, we will create set and get methods for the properties in Employee class. Please feel free to add your comments and suggestion.

Wednesday, 5 June 2013

Introduction to Objective C and its Syntax


Hi Guys, hope all of you are doing good. In this tutorial, I am planning to discuss something about Objective C and how it differs from other programming languages. I am writing this post to help beginners who are learning Objective C to develop Mac OS X or iOS applications. Prior knowledge of OOPS will help to understand Objective C better. Apple have used Objective C for their OS X, iOS and to develop their frameworks COCOA(MAC) and COCOA Touch(iOS) frame works.

Object Oriented Language :

Objective C is Object Oriented C. C is a structured language. We can't create classes and objects in C. Where as in Objective C we can create classes, objects etc how other object oriented languages are doing. Objective C is super set of C. We can compile any C program using a Objective C complier and we can write any C code inside a Objective C class.

Message Passing :

Objective C uses message passing instead of method calling  which is different from other languages like C++, Java etc. Message passing means, the target of the message is resolved during run time. System resolves during run time whether the receiver responds to the method or not. This helps in attaining dynamic binding. In Objective C, if you send a message to nil, it will simply discard the message and nothing happens. Where as in Java, you will get a run time exception.

Syntax :

Objective C syntax differs from Java, C++ and other Object Oriented languages. It follows Small talk kind of syntax. When comes to using primitive data types(int, float, char etc) it follows C syntax.

Lets suppose there is a method called firstName in class Employee. Following code snippet shows how Objective C syntax looks like to send setFirstName message to object emp of class Employee :

Objective C :

// Method Syntax
- (NSString *)firstName
{
return firstName;
}

// Message Passing
[emp firstName];

Java :

// Method Syntax
String firstName()
{
return firstName;
}

// Method Calling
emp.firstName();

C++ :

// Method Syntax
string firstName
{
return firstName;
}

// Method Calling
emp->firstName();

Now, take a look at syntax of method having single argument. Lets say, setSalary with int argument.

Objective C :

// Method Syntax
- (void)setSalary:(int)aSalary
{
}

//  Message Passing
[emp setSalary:10000];

Java :

// Method Syntax
void setSalary()
{
}

// Method Calling
emp. setSalary(1000);

 C++ :

// Method Syntax
void setSalary()
{
}

// Method Calling
emp-> setSalary(1000);

Now, take a look at syntax of method having multiple arguments. For method to set firstName and lastName of employee :

Objective C :

// Method Syntax

- (void)setFirstName:(NSString *)fName andLastName:(NSString *)lName
{
}

// Message passing
[emp setFirstName:fName andLastName:lName];

Java :

// Method Syntax
void setFirstNameAndLastName(String fName, String lName)
{
}

// Method Calling
emp. setFirstNameAndLastName(fName,lName);

C++ :

// Method Syntax
void setFirstNameAndLastName(string fName, string lName)
{
}

// Method Calling
emp->firstName(fName,lName);

Interfaces and implementations

In Objective C, each class has two sections. One is interface and other one is implementation. As per coding conventions, interface will be placed in "Header(.h)" file and implementation placed in "Implementation(.m)" file.

We will continue with Employee class. Interface for an Employee class will look like below:


Interface :

@interface Employee
{
         // Instance variables
         NSString *firstName;
         NSString *lastName:
}

// Instance Methods
- (NSString *)firstName;
- (NSString *)lastName;

- (void)setFirstName:(NSString *)firstName;
- (void)setLastName:(NSString *)lastName;

// Class Methods
+ (int)numberOfEmployees;

@end

Implementation :

@implementation Employee

// Instance Methods
- (NSString *)firstName
{

}

- (NSString *)lastName
{

}

- (void)setFirstName:(NSString *)firstName
{

}

- (void)setLastName:(NSString *)lastName
{

}

// Class Methods
+ (int)numberOfEmployees
{

}


@end

NSObject is the root class of all Objective C classes. Each class of Objective C is inherited from root class NSObject.

Thats all for now. I hope you guys got good understanding about Objective C. Please feel free to add your comments and suggestions.

In our next topic, we will cover constructors and creating objects in Objective C.

Monday, 3 June 2013

Custom Split View with Animation

Hi All,

Hope you guys are doing well. In our last tutorial Custom Split View , we have discussed about creating a custom split view controller which will show both Master and Detail views at a time. I hope all of you guys have enjoyed that tutorial.

In this tutorial, we will add some UIView animations to the Custom Split View which we have created last week. If user applies a left gesture on the split view, it will hide the "Master View", if user applies a right gesture, it will show the "Master View".

Okay, lets start. Please open the Custom Split View class MLKSplitViewController class we have created. Create two gesture recognizers(one for left and other one for right) and a BOOL property to keep track the status of Master View. 

@property(nonatomic,retain) UISwipeGestureRecognizer *leftSwipeGestureRecognizer;

@property(nonatomic,retain) UISwipeGestureRecognizer *rightSwipeGestureRecognizer;

@property(nonatomic,assign) BOOL isMasterViewHidden;

Synthesize newly created properties :

@synthesize leftSwipeGestureRecognizer;
@synthesize rightSwipeGestureRecognizer;

@synthesize isMasterViewHidden;



In - (void)viewDidLoad method add the code to create gesture recognizers and hooking up with appropriate action methods :

    // Add left gesture recognizer
    self.leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(hideMasterView:)];
    [self.leftSwipeGestureRecognizer setDirection:UISwipeGestureRecognizerDirectionLeft];
    [self.view addGestureRecognizer:leftSwipeGestureRecognizer];

    // Add right gesture recognizer
    self.rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(showMasterView:)];
    [self.rightSwipeGestureRecognizer setDirection:UISwipeGestureRecognizerDirectionRight];
    [self.view addGestureRecognizer:rightSwipeGestureRecognizer];

Now, implement the two actions for gesture recognizers and corresponding utility method :


#pragma mark -
#pragma mark - Gestures

- (IBAction)hideMasterView:(id)sender
{
    if( !isMasterViewHidden )
    {
        [UIView animateWithDuration:1.0 animations:^{
        
            [self setMasterViewFrame: CGRectMake(-MASTER_VIEW_WIDTH,0, MASTER_VIEW_WIDTH, self.view.bounds.size.height) detailViewFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
        }];
        
        isMasterViewHidden = YES;
    }
    
}

- (IBAction)showMasterView:(id)sender
{
    if( isMasterViewHidden )
    {
        [UIView animateWithDuration:1.0 animations:^{
                        
            [self setMasterViewFrame:CGRectMake(0,0, MASTER_VIEW_WIDTH, self.view.bounds.size.height) detailViewFrame:CGRectMake(MASTER_VIEW_WIDTH + SPLIT_GAP, 0, self.view.bounds.size.width - MASTER_VIEW_WIDTH - SPLIT_GAP, self.view.bounds.size.height)];
        }];
        
        isMasterViewHidden = NO;
    }
}

- (void)setMasterViewFrame:(CGRect)masterViewFrame detailViewFrame:(CGRect)detailViewFrame
{
    UIViewController *masterViewController = [self.viewControllers objectAtIndex:0];
    UIViewController *detailViewController = [self.viewControllers objectAtIndex:1];
    
    masterViewController.view.frame = masterViewFrame;
    detailViewController.view.frame = detailViewFrame;
}

Change the implementation of the - (void)layoutSubviews method according to the newly added utility method - (void)setMasterViewFrame:(CGRect)masterViewFrame detailViewFrame:(CGRect)detailViewFrame :

- (void)layoutSubviews
{
    if( !isMasterViewHidden )
    {
        [self setMasterViewFrame:CGRectMake(0,0, MASTER_VIEW_WIDTH, self.view.bounds.size.height) detailViewFrame:CGRectMake(MASTER_VIEW_WIDTH + SPLIT_GAP, 0, self.view.bounds.size.width - MASTER_VIEW_WIDTH - SPLIT_GAP, self.view.bounds.size.height)];
    }
}

We are done with the coding, lets see how output looks :
 Now apply a left swipe. See the output. "Master View" is hidden!!!!!!!!!!.
 Apply a right swipe. See the output. "Master View" is shown!!!!!!!!!!.
 Apply left and right swipes in landscape mode. Results are same as portrait!!!!!!


Hope you guys have enjoyed this tutorial about Custom Split View with Animation. Please feel free to add your comments and suggestions.

You can find source code here Source Code .



Sunday, 26 May 2013

Custom Split View for iOS

Hi Guys,

This tutorial explains you how to create a custom split view controller in iOS. Default UISplitViewController will hides some part of Details part when we see Master view in portrait mode.
I got some requirement in one of my project to show Master and Detail views completely in both portrait and landscape modes. So, I have googled some of the technical tutorials about custom split view, got inspiration and came up with a custom split view controller, which we are going to discuss now. It will display both Master and Detail views in portrait and landscape modes without hiding any content.

NOTE : From iOS 5.0 there is a new delegate method - (BOOL)splitViewController:(UISplitViewController *)svc shouldHideViewController:(UIViewController *)vc inOrientation:(UIInterfaceOrientation)orientation added to UISplitViewControllerDelegate.
By implementing this delegate method we can make both Master and Detail views appear in both landscape and portrait modes. The reason I went for custom split view controller is to have provision  for customization.

Okay, here I start. Lets create a empty application.
Give product name and select ARC.
Okay, now create a subclass of UIViewController called MLKViewController. I have a habit of creating a subclass of UIViewController which will be super class for all my ViewControllers present in my project. I will keep all common code there.


MLKViewController implementation :


Now, create Master View. Master View contains a table view with 10 rows. If we select a particular row in master view that corresponding row details will be displayed in detail row.


MasterViewController implementation :

Here is the view hierarchy for Master View :


Create Detail View. Detail View will just have a UILabel which displays the contents of the selected row in Master View.


DetailViewController implementation :

Here is the view hierarchy for Master View :


Here comes the actual piece. Creating our custom Split View Controller. This class has a initializer method which accepts two View Controllers.

Implementation of MLKSplitViewController :


I am not using any xib for our split view. I am loading the view programmatically by overriding "loadView" method. You can add your split view customization code here.  I have overridden other View Controller life cycle methods too.


I have overridden methods related to Orientation.


Hmmmm!!!! here is the actual layout code. This method takes care of laying out master view and detail view on split view. I have applied simple mathematics and its very easy to understand.


In AppDelegate, create split view controller, corresponding view controllers and hook it up with the window.



 Ok. Now we will run and see the actual output :


I hope you guys have enjoyed the tutorial. It is easy to use and simple to customize. In our next tutorial, we will add animations to show/hide the Master View.

 Please feel free to add your comments and suggestions. You can find source code here Source Code




















Saturday, 25 May 2013

Starting iOS/iPhone Programming

Hi Guys,

This tutorial is purely targeted for programmers who are planning to start iOS programming. Okay, lets start now. First see what are the pre-requisites of iOS programming :

1. Understanding of Object Oriented Concepts.
2. Mac Machine
3. Some spare time....

Apple providing a lot of frameworks to programmers to develop third party iOS applications. You can find list of available frameworks here http://developer.apple.com/library/ios/#documentation/miscellaneous/conceptual/iphoneostechoverview/iPhoneOSFrameworks/iPhoneOSFrameworks.html

All these frameworks are written in Objective C programming language. So, to build an iOS application we need learn Objective C. We will discuss more about Objective C in our next tutorials.

For now lets build an simple iOS application to give a better understanding of the tools we use to build iOS/iPhone/iPad applications.

XCode : This is the IDE we use to develop iOS applications. This is where we can write code, debug, compile and execute.
Interface Builder : For the benefit of iOS programmer, Apple provided interface builder feature to drag-drop UI elements instead of writing code to create them. If we want we can write code to programmatically create UI components though. Earlier this is independent application till Xcode 3.x. From Xcode 4.x Interface builder is integrated into Xcode itself. (See right bottom corner. U will see UI elements like label, button etc).
iPhone and iPad Simulators : Ok, here comes the actual component. Simulators!!!! If we develop an web application we will see the output on a web browser. Similarly, if we want to see output of an iOS application, we have iPhone/iPad simulators. We can use real iPhone/iPad devices also to test the output. But to do that we need a apple developer account(https://developer.apple.com/). We will see how to run an iOS applications on a real device in our future tutorials.





















Okay, now first create a XCode project. Select, Xcode from dock. From top menu, select File -> New -> Project

Select Single View Application

Give Project name, Organization Name and select iPhone in devices option. Uncheck all the check boxes. We will do examples related those in next tutorials.
Now, lets select ViewController.xib from the project navigator menu of XCode. It is a interface builder file. We can drag and drop UI elements on to the xib file. Drag and drop a label and set its properties from the properties view which appears above the elements group.

Lets center align label text and give text as "My First iOS Application". You can give label text by double clicking on the label or assigning text to "Text" property in properties view.

Now using color panel, change the background color of the view to white color.



Now run the iPhone application using command "Cmd+R" keys or by clicking the Run button appears on top left corner of the XCode. You see out put on iPhone simulator. (iPhone 3.5 inches).


Following screen shows output for iPhone 5(4 inches) retina display.


I hope you guys have enjoyed the tutorial. Please feel to add your comments. Please download source code from here MyFirstiOSApplication Source Code