Thursday, April 17, 2014

Define private property, instance variable and method in objective c

In addtion to public property and method,  public, protected, and private instance can also be defined in objective C header files, and the public and protected instance variable can be accessed by object->instanceVariable from other class or its subclass. Within the same class implementation, the private instance can be accessed either using self->privateVariable or privateVariable directly. The recommended way is self->privateVariable to avoid mixing with local variable with the same name.

Private method, property and instance variable that should not be exposed by header file should be defined in implementation .m file. The class extension can be used to define private property and private method. But private instance variable has to be defined different.

The below sample .h and .m file includes the most common usage

Header file
@interface TestObj : NSObject{
//define instance variables in header file
@public
    NSString* publicInstanceVariable;
@protected
    NSString* protectedInstanceVaraible;
@private
    NSString* privateInstanceVarialble;
}

//define public property
@property (readwrite) NSString* publicProp;

//define public methods
-(NSString*) getPublicProp;
-(void)setInstanceVariable:(NSString*)var;
-(void)setPrivatePropMethod:(NSString*)var;
-(NSString*)getInstanceVariable;
-(NSString*)getPrivateProp;
-(NSString*)callPrivateMethod:(NSString*)parm;
@end

Implementation file
#import "TestObj.h"

@interface TestObj()
    //define private property
    @property NSString* privateProp;

    //define private method
    -(NSString*) privateMethod:(NSString*)parm;
@end

//define private instance variable in .m file
@implementation TestObj{
    NSString* privateInstanceVariable;
}

//implement private method
-(NSString*) privateMethod:(NSString*)parm{
    self->privateInstanceVariable = parm;
    return self->privateInstanceVariable;
}

//implement public method
-(NSString*) getPublicProp{
    return self.publicProp;
}

-(void)setInstanceVariable:(NSString*)var{
    self->privateInstanceVariable = var;
}

-(void)setPrivatePropMethod:(NSString*)var{
    self.privateProp = var;
}

-(NSString*)getInstanceVariable{
    return self->privateInstanceVariable;
}

-(NSString*)getPrivateProp{
    return self.privateProp;
}

-(NSString*)callPrivateMethod:(NSString*)parm{
    return[self privateMethod:parm];
}

@end

Note: class extension is a special case of category without a name; that is, no name is specified between
the ( and ) . class extension can extend the class by adding additional private properties. This is not allowed for named categories

1 comment:

  1. Your blogs are great.Are you also searching for nursing pico writing help? we are the best solution for you. We are best known for delivering nursing writing services to students without having to break the bank.

    ReplyDelete