微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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、效果

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐