Objective-C允許定義協議,聲明預期用於特定情況的方法。 協議在符合協議的類中實現。
一個簡單的例子是網路URL
處理類,它將具有一個協議,其中包含processCompleted
委託方法等方法,當網路URL提取操作結束,就會調用類。
協議的語法如下所示 -
@protocol ProtocolName
@required
// list of required methods
@optional
// list of optional methods
@end
關鍵字@required
下的方法必須在符合協議的類中實現,並且@optional
關鍵字下的方法是可選的。
以下是符合協議的類的語法 -
@interface MyClass : NSObject <MyProtocol>
...
@end
MyClass
的任何實例不僅會回應介面中特定聲明的方法,而且MyClass
還會為MyProtocol
中的所需方法提供實現。 沒有必要在類介面中重新聲明協議方法 - 採用協議就足夠了。
如果需要一個類來採用多個協議,則可以將它們指定為以逗號分隔的列表。下麵有一個委託對象,它包含實現協議的調用對象的引用。
一個例子如下所示 -
#import <Foundation/Foundation.h>
@protocol PrintProtocolDelegate
- (void)processCompleted;
@end
@interface PrintClass :NSObject {
id delegate;
}
- (void) printDetails;
- (void) setDelegate:(id)newDelegate;
@end
@implementation PrintClass
- (void)printDetails {
NSLog(@"Printing Details");
[delegate processCompleted];
}
- (void) setDelegate:(id)newDelegate {
delegate = newDelegate;
}
@end
@interface SampleClass:NSObject<PrintProtocolDelegate>
- (void)startAction;
@end
@implementation SampleClass
- (void)startAction {
PrintClass *printClass = [[PrintClass alloc]init];
[printClass setDelegate:self];
[printClass printDetails];
}
-(void)processCompleted {
NSLog(@"Printing Process Completed");
}
@end
int main(int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
SampleClass *sampleClass = [[SampleClass alloc]init];
[sampleClass startAction];
[pool drain];
return 0;
}
執行上面示例代碼,得到以下結果 -
2018-11-16 03:10:19.639 main[18897] Printing Details
2018-11-16 03:10:19.641 main[18897] Printing Process Completed
在上面的例子中,已經看到了如何調用和執行委託方法。 它以startAction
開始,當進程完成,就會調用委託方法processCompleted
以使操作完成。
在任何iOS或Mac應用程式中,如果沒有代理,將永遠不會實現程式。 因此,要是瞭解委託的用法。 委託對象應使用unsafe_unretained
屬性類型以避免記憶體洩漏。
上一篇:
Objective-C擴展
下一篇:
Objective-C動態綁定