網路城邦
上一篇 回創作列表 下一篇   字體:
Objective-C的Protocol
2011/03/03 09:44:30瀏覽1409|回應0|推薦0


在寫Objective-C程式的時候,我如果希望請某物件執行doSomething方法:
 [aObject doSomething];
但aObject是否能執行doSomething方法?如果aObject 所屬的類別沒有實作 doSomething方法,那程式就會發生錯誤了。
而某個protocol如果有宣告doSomething方法,那採用這個protocol的類別的物件就一定實作了doSomething, 所以我如果需要執行doSomething,就只要挑具有這個protocol的物件就一定可行了。

還是用實際例子會比較容易讓人明白protocol的意義。Studding這個protocol裡面宣告了studyMath, studyEnglish, StudyPlayTVGame三個方法:
@protocol Studding
-(void) studyMath;
@optional
-(void) StudyPlayTVGame;
@required
-(void) studyEnglish;
@end
在這個宣告中,studyMath, studyEnglish 是必要的 (required,在protocol宣告的方法預設為required) ,而studyPlayTVGame為可選項目 (optional) 的。
而如果Student 類別採用了這個protocol,則必要的方法就會要求一定要實作。沒有這麼實作時,編譯器也會有訊息提醒。接下來是採用Studding 的例子:
@interface Student: NSObject<Studding>
@end
Student類別採用了Studding這個protocol,所以在實作的時候,studyMath和studyEnglish就一定要實作它們:
@implementation Student
-(void)studyMath{
NSLog(@"Student study Math");
}
-(void)studyEnglish{
NSLog(@"Student study English");
}
@end
那麼,我需要找一個能執行studyMath的物件,Student類別的物件就能合乎我的要求。
id<Studding> aObject;
aObject就是代表具有Studding Protocol的物件。

NSObject class有conformsToProtocol:方法來檢查物件是否為帶有某protocol的物件。如檢查aGuy是否為帶有Studding Protocol:
if ([aGuy conformsToProtocol:@protocol(Studding)]==YES)
  [aGuy studyMath];
....

一個物件可以帶有多個protocol:
@interface: AClass :ParentClass <Cooking, Baking, Mixology>{
...
}
...
@end

也可以用在Category上面:
@interface:AClass (Category) <protocol1, protocol2, ...>
....
@end

Protocol也有繼承性質:
@protocol A
MethodsOfAProtocol;
@end

@protocol B <A>
MethodsOfBProtocol;
@end

這時B protocol就包含了所有A protocol所定義的方法。所以在實作具有B protocol的類別時,MethodsOfAProtocol 與MethodsOfBProtocol通通都需要實作。
( 知識學習其他 )
回應 推薦文章 列印 加入我的文摘
上一篇 回創作列表 下一篇

引用
引用網址:https://classic-blog.udn.com/article/trackback.jsp?uid=paraquat&aid=4940273