Thursday, May 27, 2010

Objective-C Part 1

Extension ใน objective-c
.h = header file ที่จัดเก็บ header file,function,type,constant,declaretion
.m = objective-c code และ c
.mm = ที่จัดเก็บ code ที่เป็น c++

การประกาศ class ใน objective-c

@interface Dog{
NSString *name;
NSString *origin;
}

//Region properties
@property (retain) NSString *name;
@property (retain) NSString *origin;
//Region method
-(void)run:(int) speed;
@end

การ Implement class

@Implement Dog
@synthesize name,origin;
-(void)run:(int) speed){
NSLog("Dog run speed %@",speed);
}
@end

ทั้ง interface และ implement class สามารถอยู่ไฟล์เดียวกันและเเยกไฟล์กันก็ได้
ถ้าเเยกไฟล์ interface class จะอยู่ใน .h
@synthesize เพื่อบอกให้ compiler gen setter และ getter method ของ properties

การสร้าง object สามารถทำได้โดย

Dog *dog1 =[[Dog alloc] init];


การเรียกเมธอดหรือส่งเมจเสจ

[dog1 speed:5];


โปรโตคอลและเดลิเกต
สัญญลักษณ์ ของโปรโตคอล @protocal โปรโตคอล คือ การประกาศเมธอดที่คลาสอื่นสามารถนำไป implement ได้
อาจจะคล้ายๆ กับ abstract ใน java ซึ่งตัวโปรโตคอลนี้ไม่สามารถเป็นคลาสได้ด้วยตัวมันเอง การประกาศโปรโตคอล
จะมีลักษณะคล้าย interface และ object ตัวอื่นสามารถที่จะตอบสนองเมธอดของโปรโตคอลได้ด้วย การ implement
เมื่อคุณ implement method ของ protocal ในคลาสและคลาสคุณจะทำงานร่วมกันได้กับโปรโตคอล
และลักษณะการประกาศโปรโตคอล

@protocal MyProtocal
-(void) myProtocalMethod;
@end


ิติดตาม Part 2 ต่อครับ

No comments: