加入收藏 | 设为首页 | 会员中心 | 我要投稿 汽车网 (https://www.0577qiche.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

IOS之学习笔记十五(协议和委托的使用)

发布时间:2023-03-25 11:35:07 所属栏目:教程 来源:
导读:IOS之学习笔记十五(协议和委托的使用)

1、协议和委托的使用
1)、协议可以看下我的这篇博客

2)、委托可以叫代理,实现协议的类的对象可以叫委托对象或者代理对象

3)、关键就是我们在控制器里类(获取数据类)
IOS之学习笔记十五(协议和委托的使用)

1、协议和委托的使用
1)、协议可以看下我的这篇博客

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
 

(编辑:汽车网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章