天天看點

IOS之學習筆記十五(協定和委托的使用)

1、協定和委托的使用

1)、協定可以看下我的這篇部落格

IOS之學習筆記十四(協定的定義和實作)

https://blog.csdn.net/u011068702/article/details/80963731

2)、委托可以叫代理,實作協定的類的對象可以叫委托對象或者代理對象

3)、關鍵就是我們在控制器裡類(擷取資料類)裡面的成員變量需要是一個委托對象或者代理對象

4)、然後調用控制器裡類(擷取資料類)裡面的方法的時候會調用委托對象裡面定義的方法

2、測試app啟動彈框提示

1)、control.h

#ifndef Control_h

#define Control_h

#import <Foundation/Foundation.h>

//協定定義

@protocol UpdateAlertDelegate

-(void)updateAlert;

@end

@interface Control : NSObject

//遵循協定的一個代理變量定義

@property (nonatomic, weak) id<UpdateAlertDelegate> delegate;

- (void) willShowAlert;

#endif /* Control_h */

2)、control.m

#import "Control.h"

@implementation Control

- (void) willShowAlert

{

   [self.delegate updateAlert];

}

3) 、我們在ViewController.h檔案裡面實作在control.h檔案裡面定義的協定

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UpdateAlertDelegate>

4)、在ViewController.m檔案裡面實作協定的定義的方法,而且執行個體化對象設定自己為委托對象

#import "ViewController.h"

@interface ViewController ()

@implementation ViewController

- (void)viewDidLoad {

   [super viewDidLoad];

   Control *control = [Control new];

   control.delegate = self;

   [control willShowAlert];

- (IBAction)ui:(id)sender {

   NSLog(@"hello word");

- (void)didReceiveMemoryWarning {

   [super didReceiveMemoryWarning];

   // Dispose of any resources that can be recreated.

- (void)updateAlert

   UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"協定和代理" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];

   alert.alertViewStyle=UIAlertViewStyleDefault;

   [alert show];

3、效果

IOS之學習筆記十五(協定和委托的使用)

繼續閱讀