2010-03-02 64 views
1

我對iPhone中的@protocol ---- @ end感到困惑,究竟是什麼意思。我們爲什麼使用這個。它是一個功能,提供額外的方法,以一個類..?我不確定。iPhone SDK中的協議

請幫幫我。

感謝,

世斌

+0

另請參閱此問題:http://stackoverflow.com/questions/1913935/what-are-the-arrow-brackets-in-an-obj-c-class-interface-for – 2010-03-03 02:46:20

回答

9

協議用於聲明所使用由許多對象或類,其是要的官能度。

考慮一個例子,您正在開發一個鳥類數據庫。所以你會把這隻鳥作爲基礎班,你會繼承這隻鳥來創造你自己的鳥。所以在鳥類中,你將不會有任何定義,但是所有鳥類必須繼承的一些行爲。像鳥可以飛,有這樣的翅膀。那麼你將會怎樣聲明所有這些行爲並在你的派生類中實現它們。因爲可能會有飛行高度和長距離的鳥類,有些會飛行很短的距離。

爲了達到這個目的,使用@protocol。使用@protocol聲明一些行爲。在你的其他類中使用這些行爲來實現行爲。

這樣可以避免一次又一次地聲明同一個方法的開銷,並確保您在類中實現該行爲。

+0

這是一個不錯的職位..並非常明確的解釋 – 2012-09-18 10:19:30

6

@protocol等同於Java的接口。

@protocol Printable // Printable interface 
- (void) print; 
@end 

@interface MyClass: NSObject <Printable> { ... } 
// MyClass extends NSObject implements Printable 
5

@protocol可以用來定義一個委託。

例如:

@protocol SomeDelegate 
- (void)delegateActionCompleted; 
@end 

@interface MyClass: NSObject { 
    id<SomeDelegate> _delegate; 
} 
@end 

然後執行(.M)文件:

@implementation MyClass 

- (void)performAction { 
    // do the actual work 
    if (self._delegate && [self._delegate respondsToSelector:@selector(delegateActionCompleted)]) { 
     [self._delegate delegateACtionCompleted]; 
    } 
} 
@end 
0

應該更好地使用像

if (self.delegate && [self.delegate conformsToProtocol:@protocol(YourProtocolName)]) { 
    ... 
} 

檢查委託是否真正符合規定的協議。