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;
@end
#endif /* Control_h */


2)、control.m

#import <Foundation/Foundation.h>
#import "Control.h"
@implementation Control

- (void) willShowAlert
{
    [self.delegate updateAlert];
}

@end


3) 、我们在ViewController.h文件里面实现在control.h文件里面定义的协议

#import <UIKit/UIKit.h>
#import "Control.h"

@interface ViewController : UIViewController<UpdateAlertDelegate>


@end




4)、在ViewController.m文件里面实现协议的定义的方法,而且实例化对象设置自己为委托对象

#import "ViewController.h"
#import "Control.h"

@interface ViewController ()


@end

@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];
}
@end




3、效果


猜你喜欢

转载自blog.csdn.net/u011068702/article/details/80963731