Posted
Filed under iphone
Object-C 에서의 메서드 구현에는 정확히 딱 두가지가 있는것 같습니다.

바로 Class Method와 Instance Method인데요. 이 두가지 메서드는 Java로 따져보면 static 메서드와 일반 메서드로 구분될 수 있겠다고 생각합니다.

우선 테스트 코드를 작성하기 위해 Mac OS X이하의 Command Line UtilityFoundation Tool 프로젝트를 생성합니다.

보통 C++하실때 보는 콘솔 어플리케이션쯤으로 생각하시면 되겠네요.

우선 MethodTest라는 Object-C 클래스를 추가합니다.

MethodTest.h
#import <Cocoa/Cocoa.h> 
 
@interface MethodTest : NSObject { 
 
} 
+ (void)printWithClassMethod; 
- (void)printWithInstanceMethod; 
 
@end

MethodTest.m
#import "MethodTest.h" 
 
@implementation MethodTest 
 
+ (void)printWithClassMethod { 
    NSLog(@"Running with class method"); 
} 
- (void)printWithInstanceMethod { 
    NSLog(@"Running with instance method"); 
} 
 
@end

이제 main 함수에 다음과 같이 기록해 봅시다.
#import <Foundation/Foundation.h> 
#import "MethodTest.h" 
 
int main (int argc, const char * argv[]) { 
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
 
    // insert code here... 
    [MethodTest    printWithClassMethod]; 
    MethodTest *mt = [MethodTest alloc]; 
    [mt printWithInstanceMethod]; 
     
    [pool drain]; 
    return 0; 
}

감이 오시나요? printWithClassMethod는 클래스를 인스턴스화 하지 않고도 호출할 수 있는 메서드입니다.

하지만 printWithInstanceMethod는 꼭 초기화 된 상태에서 호출해야만 하죠.

이를 자바로 한번 풀어보면 다음과 같겠죠.
class MethodTest { 
    public static void printWithClassMethod() { 
        System.out.println("Running with class method"); 
    } 
    public void printWithInstanceMethod() { 
        System.out.println("Running with instance method"); 
    } 
}

[원문 ] - http://theeye.pe.kr/entry/iPhone-Object-C-Class-Method-VS-Instance-Method?category=26
2011/06/07 20:21 2011/06/07 20:21