怎麼自己在Objective-C中建立代理,objective-c建立

來源:互聯網
上載者:User

怎麼自己在Objective-C中建立代理,objective-c建立

首先我們要先建立一個類,為了方便理解我們就類比現實生活中的找中介租房子,因此先建立一個Person類

1.在Person.h中定義代理的協議,並完成代理方法聲明:代碼如下

 1 // Person.h檔案 2  3 #import <Foundation/Foundation.h> 4  5 @class Person; 6  7 //1 定義代理的協議 8 @protocol PersonDelegate <NSObject> 9 10 // 可選方法11 @optional12 - (void)personFindHouse:(Person *)person;13 // 必要方法14 @required15 16 @end17 18 @interface Person : NSObject19 20 @end

註:代理協議中可選方法可實現可不實現,但必要方法必須實現

2、定義代理屬性:代碼如下

 1 // Person.h檔案 2   3 #import <Foundation/Foundation.h> 4 @class Person; 5 //1 定義代理的協議 6 @protocol PersonDelegate <NSObject> 7 // 可選方法 8 @optional 9 - (void)personFindHouse:(Person *)person;10 // 必要方法11 @required12 13 @end14  15 @interface Person : NSObject16 @property (nonatomic,copy) NSString *name;17 //2 定義代理屬性18 @property (nonatomic,weak) id<PersonDelegate> delegate;19 - (void)zuFang;20 @end

3、調用代理的方法(通知) 給代理髮送訊息:代碼如下

 1 // Person.m檔案 2 #import "Person.h" 3  4 @implementation Person 5 - (void)zuFang 6 { 7     NSLog(@"%@--要租房",self.name); 8      9     //3 調用代理的方法(通知) 給代理髮送訊息10     if([self.delegate respondsToSelector:@selector(personFindHouse:)])11     {12         [self.delegate personFindHouse:self];13 14     }15 }16 @end

上面代碼第10行是判斷這個對象是否實現了personFindHouse:這個方法

好現在我們需要定義一個ZhongJie類來使用這個代理

1、讓這個類遵守代理協議:代碼如下

1 // ZhongJie.h檔案2 #import <Foundation/Foundation.h>3 #import "Person.h"4 5 @interface ZhongJie : NSObject <PersonDelegate>6 7 @end

2、實現代理方法:代碼如下

 1 // ZhongJie.m檔案 2 #import "ZhongJie.h" 3  4 @implementation ZhongJie 5  6 - (void)personFindHouse:(Person *)person 7 { 8     NSLog(@"找到房子了 "); 9 }10 11 @end

3、設定代理屬性:代碼如下

 1 // ViewController.m 檔案 2 #import "ViewController.h" 3 #import "Person.h" 4 #import "ZhongJie.h" 5 @interface ViewController () 6  7 @end 8  9 @implementation ViewController10 11 - (void)viewDidLoad {12     [super viewDidLoad];13     // Do any additional setup after loading the view, typically from a nib.14     ZhongJie *zj = [[ZhongJie alloc] init];15     16     Person *p = [[Person alloc] init];17     18     p.name = @"someOne";19     //3 設定代理屬性20     p.delegate = zj;21     22     [p zuFang];23     24 }25 26 27 @end

 

這樣我們就建立了代理,並讓一個對象使用了這個代理

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.