iOS中 委託 代理 協議 的理解

一、協議:協議不是類,是一種約定,他聲明的方法和屬性,都是獨立於其餘任何特定的類,並自己不會去實現他,讓使用他的類去實現他,好比UITableView,須要實現他的cellForRowAtIndexPath等協議,誰用誰知道。xcode

協議的兩個預編譯指令@optional:能夠選擇的方法。@required:必須執行的方法。
ui

咱們打開UITableView的頭文件,看下他的聲明:atom

@protocol UITableViewDataSource<NSObject>

@required

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

能夠看到,這些方法是協議要求你必須實現的。spa

如今來看看寫週報的事,
代理

咱們新建一個類,Workcode

在Work.h頭部申明要寫週報(協議)對象

Work.h:ci

#import <Foundation/Foundation.h>
@protocol Weekly <NSObject>;
@required
-(NSString *)Progress;
@optional
-(NSString *)Advice;
@end
@interface Work : NSObject

@end

Weekly協議裏面有個方法,就是Progress"進度",並且是@required的強制要求實現的get

還有一個方法 Advice "建議",是@optional可實現可不實現it

注意一點,<NSObject>是遵循NSObject協議,不是NSObject類

二、委託

假設主管是A類

A.h裏面:

#import "Work.h"
@interface A : NSObject
//定義一個委託代理
@property (nonatomic) id <Weekly> delegate;
@end

@property (nonatomic) id <Weekly> delegate;

就像主管開會,宣佈了一個任務 :delegate,這個任務就是要寫週報 :<Weekly>

接下來分配

員工B類、C類、D類等,我就指寫一個B類作例子

A.m裏面:

#import "A.h"
//導入B
#import "B.h"
@implementation A
-(instancetype)init{
    self = [super init];
    //實例化員工B
    B* b = [[B alloc] init];
    //設置代理的實現者是B員工對象,等於分配任務給他
    self.delegate = b;
    //主管查看B員工的週報
    NSString* B_Progress = [b Progress];
    NSString* B_Advice = [b Advice];
    NSLog("%@",B_Progress);
    NSLog("%@",B_Advice);
    return self;
}

咱們會發現self.delegate = b; 會有警告,爲何呢?由於B員工如今還只是員工B,不是已經投入寫週報的B員工,由於他還沒接受你這個任務,是否是?我作不作那是個人事,你交代給我我不作,那你就麻煩了,我能夠不寫,大不了不幹是吧?跟上級有衝突的屌絲就是這樣,各類理由各類反駁,若是B接受任務,就要受寫週報約束,來看下

B.h裏面:

//導入協議類
#import "Work.h"
//<Weekly>遵循週記的協議,必須寫週記
@interface B : NSObject <Weekly>

@end

B.m裏面實現:

//週記必須寫的內容
-(NSString *)Progress{
    return @"xxx項目進度達到90%!";
}
//可寫可不寫的內容
-(NSString *)Advice{
    return @"主管英明神武,沒有意見!";
}

這樣,B類就實現了協議的內容,完成了主管分配的任務,並返回結果。若是不實現Progress,xcode會報警告,你沒有實現這個代理。



總結:

1、協議的定義
@protocol 協議名 <NSObject>;
@required
必須實現的方法
@optional
可選實現的方法
@end
2、委託的定義
@pro
相關文章
相關標籤/搜索