[object methodWithInput:input];
리턴값이 있는 경우
output = [object methodWithOutput]
output = [object methodWithInputAndOutput:input];
-
클래스 메소드도 같은 문법으로 호출 가능예
)
id myObject = [NSString string]; (
id 타입이란? myObject가 어떤 오브젝트의 참조도될 수 있다는뜻)같은 표현으로
,
NSString* myString = [NSString string];
(
모든Objective-C
의 변소들은 포인터 타입이므로*
를 붙일 필요가 없음)
- myWidget
객체에PowerOn
이라는 메시지를 보내는 방법예
)
Objective-C returnValue = [myWidget powerOn];
C++ returnValue = myWidget
->PowerOn();
C returnValue = widget_powerOn(myWidget);
Objective-C 의 특징
Objective-C 의 특징
• 접근자
- Objective-C
의 모든 인스턴스 변수들은Private
-
즉,
접근자를 사용하여 엑세스해야 함-
일반적인 문법예
)
[photo setCaption:@”Day at the Beach”];
output = [photo caption];
//인스턴스변수를직접읽는다는뜻이아니라 caption이라는메소드를부르고있는것Objective-C에서는 일반적으로 getter 메소드에 get을 붙이지 않고 사용
- .(dot)
을 이용한 문법.(dot)은 접근자(getter and setter)를 위해 Objective-C 2.0에 새로 추가된 문법 예)
photo.caption = @”Day at the Beach”;
output = photo.caption;
• 전처리기 선언 Import
- #include
대신#import
문을 사용Objective-C 의 특징
• String
- c
의String
을 그대로 사용 가능-
그러나 대부분의Objective-C framework
에서는NSString
이라는 독자적인 클래스 사용- “
더블 쿼테이션 앞에@
만 붙여줌으로써 생성 가능예
) NSString *myString = @"My String\n";
NSString *anotherString = [NSString stringWithFormat:@"%d %s", 1, @"String"];
// Create an Objective-C string from a C string
NSString *fromCString = [NSString stringWithCString:"A C string" encoding:NSASCIIStringEncoding];
• 프로퍼티 property 선언
-
인스턴스 변수와 메소드 사이의 매개체 역할- interface
안에 메소드와 같이 정의예
)
@property (nonatomic, retain) IBOutlet UILabel *statusText;!nonatomic - 쉽게 멀티스레드를 위한 코드를 삽입하지 않아 오버헤드를 줄임 retain - Objective-C의 독특한 메모리 관리 기법 중 하나
-
implementation
파일에 @synthesize statusText;와 같은 선언을 하면 컴파일러에 의해 메소드가 자동 생성됨
Objective-C 의 특징
@interface MyClass : NSObject //인터페이스 정의 시작 {
int count;
id data;
NSString* name;
}
- (id)initWithString : (NSString*)aName;
+ (MyClass*)createMyClassWithString:(NSString*)aName;
@end //인터페이스 정의 끝
클래스명 슈퍼
클래스명
멤버변수 정의
메소드 정의
• 클래스 선언 (.h)
클래스의 interface는 .h에 정의 .m에 implementation
+메소드(클래스 메소드) - 메소드(인스턴스 메소드)
• 클래스 implementation(.m)
@implementation MyClass
-(id)initWithString:(NSString *)aName;
{
if(self = [super init]){
name = [aName copy];
}
return self;
}
+ (MyClass*)createMyClassWithString:(NSString*)aName;
{
return [[[self alloc] initWithString:aName] autorelease];
}
@end
Objective-C 의 특징
• 메소드 정의 방법
-
(void)insertObject:(id)anObject atIndex:(NSUInteger)index리턴타입
메소드타입
식별자 파라미터타입
파라미터명 메소드
식별자명
-
호출하는 예[myArray insertObject:anObject atIndex:0];
- 괄호 안에 괄호를 넣는 방법([ [] ])
쓸모없는 임시 변수를선언하지 않게 메소드의 리턴값을 파라미터로직접 넘길 수 있음
[[myAppObject theArray] insertObject:[myAppObject objectToInsert] atIndex:0];
-
.(도트)를 사용하는 방법accessor methods(단순히 클래스 멤버에 엑세스 하기 위해 만들어진 메소드, getter or setter)를 호출할 때 사용 [myAppObject.theArray insertObject:[myAppObject objectToInsert] atIndex:0];
위의 방법은 다음과 같이 사용
myAppObject.theArray = aNewArray;