Monday, September 3, 2012

Introduction to Objective-C

Refer to the first part of the tutorial from this link: http://iosmadesimple.blogspot.com/2012/07/introduction-to-xcode.html

Objectives:

  • To understand the class structure and its implementation in Objective-C
  • To get acquainted with Objective-C syntax
Objective-C uses Model-View-Controller design pattern. If you want to know more about MVC design pattern in Objective-C, refer to this link from Cocoa Lab. http://www.cocoalab.com/?q=node/24

Class Structure

  1. Interface Section - where your data components and function headers are located; found in .h files
  2. Implementation Section - where your implementation for your functions are located; found in .m files
  3. Program Section - these are your codes; where your instatiate objects to carry out your tasks

Class Definition and Instatiation Syntax

Interface (.h files)

@interface NameOfClass:ParentClass {
//instance variables
returnType nameOfVariable;
}

//instance methods
- (returnType)methodName1; //No Parameters
- (returnType)methodName2:(returnType)parameter; //With One Parameter
- (returnType)methodName3:(returnType)parameter1 ThisIsPartOfTheMethodNameWithData:(returnType)parameter2; //With MultipleParameters
@end

Implementation (.m files)

@implementation NameOfClass
- (returnType)methodName1 {
//Put your codes here
}

- (returnType)methodName2:(returnType)parameter {
//Put your codes here
}

- (returnType)methodName3:(returnType)parameter1 ThisIsPartOfTheMethodNameWithData:(returnType)parameter2 {
//Put your codes here
}
@end

Program

main.m file //Remeber to import the class you created
int main(int argc, char *argv[]) {
//Create instance of the class
NameOfClass *instanceName1 = [[NameOfClass alloc] init];

//Or you may do it this way
NameOfClass *instanceName2;
instanceName2 = [NameOfClass alloc];
instanceName2 = [NameOfClass init];

//Calling a class function
[instanceName2 methodName];
[instanceName2 methodName2:100]; //assume that the dataType of the parameter is int, let's pass integer 100

//If you no longer need the objects, release their memory
[instanceName1 release];
[instanceName2 release];
}



1 comment:

  1. I'm just learning here, but shouldn't the example Program do

    instanceName2 = [NameOfClass alloc];
    instanceName2 = [instanceName2 init];

    ReplyDelete