본문 바로가기

C/Objective C/Objective C

Objective C 정적변수 예제 따라하기

정적 변수

앞서 메서드 외부에서 정의된 변수는 전역 변수만이 아니라 외부 변수도 된다고 이미 말했다. 그러나 전역 변수이면서도 외부 변수는 되지 않기를 원하는 경우가 많다. 다시 말하면, 특정 모듈(파일)에서는 지역변수 이면서 전역으로 변수를 정의하고 싶을 때가 있다는 이야기다. 만일, 특정 클래스 정의에 포함된 메서드를 제외하고는 특정 변수에 접근할 필요가 없다면, 이런 식으로 변수를 정의해야 합당하다.

파일 내에서 특정 클래스를 구현하는 부분이 있다면 파일 안에서 변수를 정적으로 정의하여 이를 달성할 수 있다.
만일 메서드(혹은 함수) 바깥에서 다음 명령문을 사용하면, 이 정의가 나오는 파일 안에, 명령문 다음에 등 장하는 모든 지점에서는 gGlobalVar의 값을 접근할 수 있다. 그러나 다른 파일에 포함된 메서드와 함수에 서는 접근할 수 없게 된다.

static int gGlobalVar = 0;
클래스 메서드는 인스턴스 변수에 접근할 수 없음을 기억하자(여기서도 역시 마찬가지다). 그러나 클래스 메서드가 변수에 접근하고 값을 설정해야 할 때도 있다.
간단한 예로 생성한 객체의 개수를 세는 클래스 할당 메서드를 생각해 보자. 클래스의 구현 파일 내에 정 적 변수를 설정하여 이 작업을 수행할 수 있다. 할당 메서드는 인스턴스 변수에 접근할 수 없으므로 이 정 적 변수에 직접 접근하여 값을 설정한다. 클래스의 사용자는 이 변수에 대해서 무언가 알고 있을 필요가 없다.
그 이유는 구현 파일에 정적 변수로 정의되어서, 변수의 범위가 그 파일로 제한되기 때문이다. 따라서 사 용자는 이 변수에 직접 접근할 필요가 없고, 데이터 캐슐화의 개념을 위반하지도 않는다. 만일 클래스 바 깥에서 접근할 필요가 있다면 변수의 값을 받아 오는 메서드를 작성하면 된다.


- 소스코드 

#import <Foundation/Foundation.h>


@interface Fraction : NSObject

{

int numerator; int denominator;

}

@property int numerator, denominator;

+(Fraction *) allocF;+(int) count;-(Fraction *) initWith: (int) n: (int) d; -(void) print;

-(void) setTo: (int) n over: (int) d;

-(double) convertToNum;

-(void) reduce;

-(Fraction *) add: (Fraction *) f;

@end 

#import "Fraction.h"


static int gCounter;


@implementation Fraction

@synthesize numerator, denominator;


+(Fraction *) allocF { 

extern int gCounter; ++gCounter;

return [Fraction alloc]; 

}


+(int) count {

extern int gCounter;

return gCounter

}


-(Fraction *) initWith: (int) n: (int) d { 

self = [super init];

if (self)

[self setTo: n over: d];

return self

}


-(void) print {

NSLog (@"%i/%i", numerator, denominator);

}


-(double) convertToNum {

if (denominator != 0)

return (double) numerator / denominator;

else

return 1.0;

}


-(void) setTo: (int) n over: (int) d {

numerator = n;

denominator = d; 

}


-(void) reduce {

int u = numerator; int v = denominator; int temp;

while (v != 0) { temp = u % v;

u = v;

v = temp; }

numerator /= u;

denominator /= u; 

}


-(Fraction *) add: (Fraction *) f {

// To add two fractions:

// a/b + c/d = ((a*d) + (b*c) / (b * d)

// result will store the result of the addition 

Fraction *result = [[Fraction alloc] init];

int resultNum, resultDenom;

resultNum = numerator * f.denominator + denominator * f.numerator

resultDenom = denominator * f.denominator;

[result setTo: resultNum over: resultDenom]; [result reduce];

return result; 

}

@end 

#import <Foundation/Foundation.h>

#import "Fraction.h"


int main(int argc, const char * argv[])

{


Fraction *a, *b, *c;

NSLog (@"Fractions allocated: %i", [Fraction count]);

a = [[Fraction allocF] init]; 

b = [[Fraction allocF] init]; c = [[Fraction allocF] init];

NSLog (@"Fractions allocated: %i", [Fraction count]);

return 0;

} 

- 실행화면