Posing, as its name implies, means "impersonating". It is similar to categories, but essentially it is different. The purpose of posing is that sub-classes can impersonate parent classes, so that subsequent Code does not need to change the parent class to a subclass, it can easily make the parent class behave as a subclass, so as to achieve very convenient impersonating, this is hard to imagine in general languages.
It allows you to expand a class and fully impersonate this super class. For example, you have an nsarraychild object that extends nsarray. If you want nsarraychild to impersonate nsarray, the nsarray where your program code is located will be automatically replaced with nsarraychild. Note: This does not mean code replacement, but nsarray's behavior is the same as nsarraychild.
Example:
1. Define the parent class:
Fraction. h:
#import <Foundation/NSObject.h>
@interface Fraction : NSObject{
int numerator;
int denominator;
}
-(id)initWithNumeration:(int)a:denominator:(int) b;
-(void) print;
@end
Fraction. M:
#import <stdio.h>
#import "Fraction.h"
@implementation Fraction
-(id)initWithNumeration:(int)a:denominator:(int) b {
self = [super init];
if(self) {
numerator = a;
denominator = b;
}
return self;
}
-(void) print {
printf("Fraction: %i/%i", numerator, denominator);
}
@end
2. Define subclass:
Fractionchild. h:
#import "Fraction.h"
@interface FractionChild : Fraction
-(void) print;
@end
Fractionchild. M:
#import <stdio.h>
#import "FractionChild.h"
@implementation FractionChild
-(void) print {
printf("FractionChild: %i/%i", numerator, denominator);
}
@end
3. Start to impersonate fraction with fractionchild.
Main. M:
#import <stdio.h>
#import "Fraction.h"
#import "FractionChild.h"
int main (int agrc, const char * agrv []) {
Fraction * frac = [[Fraction alloc] initWithNumeration: 3: denominator: 4];
[frac print]; // The output at this time: Fraction: 3/4
// make FractionChild posing as Fracition, note: This method of poseAsClass is a built-in method of NSObject, which is used for the child class posing the parent class.
[FracitonChild poseAsClass [Fraction class]];
Fraction * frac2 = [[Fraction alloc] initWithNumeration: 3: denominator: 4];
[frac2 print]; // Output at this time: FractionChild: 3/4, and the Fration performance behavior at this time is impersonated by FractionChild
[frac release];
[frac2 release];
}