Sunday, January 19, 2014

iOS Tutorial - Part 4 - Instance variables, methods, property

Objective-C instance variables, methods and properties


Video Description
There are two popular types of classes in Objective-C language, files end with .h and files end with .m

.h files

If you want to define public variables or public methods, you need to declare them in .h file. Simple .h file would look like this.
#import <UIKit/UIKit.h>

@interface ClassName : UIViewController

@end
 UIViewContoller is the super class of our class.

.m files

If you want to define private variables or private methods, you need to declare them in .m file. Simple .m file would look like this. 
#import "ClassName.h"

@interface ClassName ()
@end

@implementation ClassName
@end 

Instance variables

Based on the type of variable, you can easily declare them in .h or .m files.
Example of declaring variables in .h file
#import <UIKit/UIKit.h>

@interface ClassName : UIViewController {
    int variableName;
}

@end
Example of declaring variables in .m file
#import "ClassName.h"

@interface ClassName (){
    int variableName;
}
@end

@implementation ClassName

@end 

Instance Methods

Example of declaring Instance methods in .h file
#import <UIKit/UIKit.h>

@interface ClassName : UIViewController {
   int variableName;
} 
-(void) myInstanceMethodName;
 @end
Example of declaring Instance methods in .m file

#import "ClassName.h"

@interface ClassName (){
    int variableName;
}
@end

@implementation ClassName
 
-(void) myInstanceMethodName
{
   //Method implementation
}
 @end

Properties

In terms of memory management it's better to use properties instead of instant variables. It's more efficient and easier to use. It also creates setter and getter by writing one line of code. You declare properties like below:
@property (nonatomic, strong) NSString *propertyName;
NSString means the property, is type of string. You need to add * before variable name. At this stage don't worry about the (nonatomic, strong), just happily use it for your properties. Later on I'll explain what are these words good for.
In order to make setter and getter for this property you need to synthesize (implement) it. You synthesize it by the following line of code:
@synthesize propertyName = _propertyName;

Example of property and synthesize in .m file
#import "ClassName.h"

@interface ClassName ()
@property (nonatomic, strong) NSString *propertyName;

@end

@implementation ClassName

@synthesize propertyName = _propertyName;

@end

No comments:

Post a Comment