[Objective C] 09 Posing

프로그래밍/iPhone Dev 2009. 11. 10. 14:35 Posted by galad
Posing
자세 잡기. 상속 관계에 있는 클래스 중에서 하위 클래스에게 상위 클래스에 대한 메시지에 응답하라고 설정하는 것.

Fraction.h
#import <Foundation/NSObject.h>

@interface Fraction: NSObject {
    int numerator;
    int denominator;
}

-(Fraction*) initWithNumerator: (int) n andDenominator: (int) d;
-(Fraction*) initWithNumerator: (int) n denominator: (int) d;
-(void) print;
-(void) setNumerator: (int) n;
-(void) setNumerator: (int) n andDenominator: (int) d;
-(void) setDenominator: (int) d;
-(int) numerator;
-(int) denominator;
@end


Fraction.m
#import "Fraction.h"
#import <stdio.h>

@implementation Fraction
-(Fraction*) initWithNumerator: (int) n andDenominator: (int) d {
    self = [super init];
   
    if(self) {
        [self setNumerator: n andDenominator: d];
    }
   
    return self;
}

-(Fraction*) initWithNumerator: (int) n denominator: (int) d {
    self = [super init];
   
    if(self) {
        [self setNumerator: n andDenominator: d];
    }
   
    return self;
}

-(void) print {
    printf( "%i/%i", numerator, denominator );
}

-(void) setNumerator: (int) n {
    numerator = n;
}

-(void) setNumerator: (int) n andDenominator: (int) d {
    numerator = n;
    denominator = d;
}

-(void) setDenominator: (int) d {
    denominator = d;
}

-(int) denominator {
    return denominator;
}

-(int) numerator {
    return numerator;
}
@end


FractionB.h
#import "Fraction.h"

@interface FractionB: Fraction
-(void) print;
@end


FractionB.m
#import "FractionB.h"
#import <stdio.h>

@implementation FractionB
-(void) print {
    printf( "(%i/%i)", numerator, denominator );
}
@end


main.m
#import <stdio.h>
#import "Fraction.h"
#import "FractionB.h"

int main( int argc, const char *argv[] ) {
    Fraction *frac = [[Fraction alloc] initWithNumerator: 3 denominator: 10];

    // print it
    printf( "The fraction is: " );
    [frac print];
    printf( "\n" );

    // make FractionB pose as Fraction
    [FractionB poseAsClass: [Fraction class]];

    Fraction *frac2 = [[Fraction alloc] initWithNumerator: 3 denominator: 10];

    // print it
    printf( "The fraction is: " );
    [frac2 print];
    printf( "\n" );

    // free memory
    [frac release];
    [frac2 release];

    system("PAUSE");
    return 0;
}


결과
The fraction is: 3/10
The fraction is: (3/10)
계속하려면 아무 키나 누르십시오 . . .

- The method poseAsClass is part of NSObject. This allows a subclass to pose as a superclass.

'프로그래밍 > iPhone Dev' 카테고리의 다른 글

[Objective C] 11 Retain and Release  (0) 2009.11.12
[Objective C] 10 Protocols  (0) 2009.11.11
[Objective C] 08 Categories  (0) 2009.11.09
[Objective C] 07 DynamicTypes  (0) 2009.10.30
[Objective C] 06 Inheritance  (1) 2009.10.30