objective-c 的私有方法

接口定义:
#import <Foundation/Foundation.h>
@interface Fraction: NSObject{
	int numerator;
	int denominator;
}
-(void) print;
-(void) setNumerator:(int) n;
-(void) setDenominator:(int) d;
-(int) numerator;
-(int) denominator;
@end

实现定义:
#import "Fraction.h"
@interface Fraction(Private)
	-(int) other;
@end
@implementation Fraction

-(int) other{
	return 9;
}

-(void) print{
	
	printf("%i/%i",numerator,denominator);
}
-(void) setNumerator:(int) n{
	numerator = n;
}

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

}

-(int) denominator{
	return denominator;
}
-(int) numerator{
	
	int cc = [self other];
	printf("this is %d",cc);
	return numerator + cc;
}

实现里面要想写私有方法,就在里面要写一个和接口一样名字的接口,
@interface Fraction(Private)
other方法就是私有方法了,[self other] 和java的 this.other()差不多;


写main函数测试
#import "Fraction.h"

int main(int argc,const char *argv[]){
	Fraction *frac = [[Fraction alloc] init];

[frac setNumerator:1];
[frac setDenominator:3];
printf("the fraction is :");
[frac print];
printf("\n");
[frac numerator];
[frac release];
return 0;

}


frac numerator就类似java的 frac.numerator (getter方法),调用后就会打印私有方法的9啦。。

你可能感兴趣的:(Objective-C)