標籤:調用 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代理模式