[an error occurred while processing this directive]

Posing

                         

Posing is similar to category but it works a little bit different with the category. It enable programmers to pose subclass to super class globally. When subclass posed on super class method which are same in both classes are override with the subclass methods.

In the example code given below we have two classes BaseClass and SubClass. Method show() is defined in both class but with different message. Before posing when we create object of base class, show method will show the output according to the base class but after posing it will display output from show method defined in sub class.

Example:

BaseClass.h  BaseClass.m
#import<Foundation/NSObject.h>
@interface BaseClass : NSObject {
    int num1, num2;
  }
  -(void)set :(int) x and: (int) y;
  -(int)add;
  -(int)sub;
  -(void)show:(int)x;
@end

 

#import"BaseClass.h"
@implementation BaseClass
  -(void)set :(int) x and: (int) y {
       num1 = x;
       num2 = y;
  }
  -(int)add {
       return num1+num2;
  }
  -(int)sub {
       if(num1>num2){
          return num1-num2;
       }
       else
          return num2-num1;
       }
  -(void)show:(int)x {
      printf("Base class result : %d \n",x);
  }
@end

 

   

 

 

 

 

    

 

 

 

 

SubClass.h  SubClass.m
#import"BaseClass.h"
@interface SubClass : BaseClass
-(void)show:(int)x;
@end

 

#import"SubClass.h"
@implementation SubClass
-(void)show:(int)x {
printf("Sub class result : %d \n",x);
}
@end

 

 

 

 

 

main.m

 
#import"BaseClass.m"
#import"SubClass.m"
#import<stdio.h>
int main(){
   // create base class object.
   BaseClass *obj1 = [[BaseClass alloc] init];
   [obj1 set:10 and:8];
   [obj1 show:[obj1 add]];
   [obj1 show:[obj1 sub]];
   // pose subclass to baseclass.
   [SubClass poseAsClass: [BaseClass class]];
   // create base class object after posing.
   BaseClass *obj2 = [[BaseClass alloc] init];
   [obj2 set:11 and:6];
   [obj2 show:[obj2 add]];
   [obj2 show:[obj2 sub]];
   // free memory
   [obj1 release];
   [obj2 release];
   return 0;
}

Output:

Base class result : 18 
Base class result : 2 
Sub class result : 17 
Sub class result : 5

Download Source Code

                         

[an error occurred while processing this directive]