Theo mình hiểu thì delegate trong Objective-C dùng để gọi 1 phương thức nằm trong 1 class khác hoàn toàn với class hiện tại.
Ví dụ trong class B có phương thức
//ClassB.m
-(void)add:(int) a and: (int)b
{
a = a+b;
}
1 Class A không là subclass của B nhưng muốn gọi phuơng thức add:and: ở trong B.
Ta thực hiện như sau:
- định nghĩa 1 protocol chứa method add:
//ClassA.h
@protocol ClassADelegate
-(int) add:(int) a and:(int) b;
@end
-khai báo 1 property kiểu id<ClassADelegate> cũng trong ClassA.h:
Code:
@property (nonatomic, assign) id<ClassADelegate> delegate;
-khai báo class B thực thi protocol ClassADelegate và tất nhiên phải implement method add:and: của protocol ClassADelegate trong ClassB.m:
//ClassB.h
@interface ClassB: NSObject<ClassADelegate>
{
...
}
...
@end
- sử dụng delegate để gọi method add
//ClassA.m
if (self.delegate && [self.delegate respondsToSelector:@selector(add:and:)]) // kiểm tra có tồn tại delegate và có responde tới method add:and: không
{
[self.delegate add:x and:y] // x,y là 2 biến kiểu int
}
Thực chất vấn đề là thông qua protocol (giống interface của java) để "liên lạc" giữa 2 class.
ClassB có thể khai báo là kế thừa từ nhiều protocol...
Mình biết nhiêu đó, có gì sai sót mong các pro bỏ quá cho ^^