iOS代理模式

來源:互聯網
上載者:User

標籤:調用   res   roc   登入   class   weak   擷取   理解   控制器   

iOS代理模式的簡單理解:當一個對象無法直接擷取到另一個對象的指標,又希望對那個變數進行一些操作時,可以使用代理模式。

代理主要由三部分組成:

(1)協議:用來指定代理雙方可以做什麼,必須做什麼。

(2)代理:根據指定的協議,完成委託方需要實現的功能。

(3)委託:根據指定的協議,指定代理去完成什麼功能。

 代理使用步驟1.申明一個協議  (這個寫在需要被擷取的對象裡面,也可以單獨寫一個類)

@protocol TextDelegate

-(void)deliverFirsttext:(NSString* )text1 withDeliverSecondtext:(NSString * )text2;

@end

 2.代理 #import #import "LoginProtocol.h" @interface LoginViewController : UIViewController   //通過屬性來設定代理對象 @property (nonatomic, weak) id delegate; @end  實現部分:  @implementation LoginViewController - (void)loginButtonClick:(UIButton *)button {        // 判斷代理對象是否實現這個方法,沒有實現會導致崩潰          if  ([self.delegaterespondsToSelector:@selector(deliverFirsttext:withDeliverSecondtext: )]) {        // 調用代理對象的登入方法,代理對象去實現登入方法              [self.delegate deliverFirsttext:self.text1.textwithDeliverSecondtext:self.text2.text ];    } } 3 設定代理方 (擷取到所需要對象) @interface ViewController ()   @end  @implementation ViewController - (void)viewDidLoad {      [ super  viewDidLoad];  } 

- (IBAction)buttonAction:(id)sender {

    SecondViewController *VC =

    [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"SecondViewController"];

    //設定當前控制器為secondVC的代理

    VC.delegate = self;

    [self presentViewController:VC animated:YES completion:^{

    }];

}

 

-(void)deliverFirsttext:(NSString *)text1 withDeliverSecondtext:(NSString *)text2{

    

    self.label1.text = text1;

    self.label2.text = text2;

}

 

實現效果:

      

 

 

 

 

iOS代理模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.