欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS 代理(Delegate)

程序员文章站 2022-04-16 15:54:06
iOS 代理(Delegate)一、二、代码实现一、创建名为DelegateDemo的class文件继承自NSObject二、代码实现DelegateDemo.h//// DelegateDemo.h// iOS代理协议与委托//// Created by apple on 2020/10/23.// Copyright © 2020 apple. All rights reserved.//#import ...

一、说明

1、代理的使用

一般用于逻辑和UI的交互。例:逻辑上增加了50金币,此时需要在UI上更新金币的显示。或者需要调用其他UIView,此例用于5秒后调用显示AlertView

创建名为DelegateDemo的class文件继承自NSObject

二、代码实现

DelegateDemo.h
//
//  ViewController.m
//  iOS 代理
//
//  Created by MangoChips on 2020/10/25.
//  Copyright © 2020 MangoChips. All rights reserved.
//

#import <Foundation/Foundation.h>

//协议定义
//定义一个代理协议 DelegateDemoProtocol 及代理方法 showDelegateAlertView
@protocol DelegateDemoProtocol <NSObject>

-(void)showDelegateAlertView;//此代理方法为 实现具体功能的方法

@end

NS_ASSUME_NONNULL_BEGIN

@interface DelegateDemo : NSObject

//遵循协议的一个代理变量定义
@property(nonatomic,weak) id<DelegateDemoProtocol> delegateDemoProtocol;

-(void)startTimer;//暴露给外部调用

@end

NS_ASSUME_NONNULL_END

DelegateDemo.m
//
//  ViewController.m
//  iOS 代理
//
//  Created by MangoChips on 2020/10/25.
//  Copyright © 2020 MangoChips. All rights reserved.
//

#import "DelegateDemo.h"

@implementation DelegateDemo

//5秒后更新UI(或金币增加更新UI面板显示)
-(void)startTimer{
    
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timerProtocol) userInfo:nil repeats:NO];
}

-(void)timerProtocol{
    
    [self.delegateDemoProtocol showDelegateAlertView];//使用代理更新UI界面
}

@end

ViewController.m
//
//  ViewController.m
//  iOS 代理
//
//  Created by MangoChips on 2020/10/25.
//  Copyright © 2020 MangoChips. All rights reserved.
//

#import "ViewController.h"

#import "DelegateDemo.h"

@interface ViewController ()<DelegateDemoProtocol>//需先遵循协议

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    DelegateDemo *delegateDemo = [[DelegateDemo alloc] init];
   delegateDemo.delegateDemoProtocol = self;
   [delegateDemo startTimer];
}

//"被代理对象"实现协议声明的方法,由"代理对象"调用
-(void)showDelegateAlertView{
    NSLog(@"5S After");
    
    //UIAlertView已经被遗弃使用,真机可以运行,模拟器会崩溃。log正常输出
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"5s 时间到" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];

    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
    
}
@end

git地址

本文地址:https://blog.csdn.net/X_King_Q/article/details/109242865

相关标签: iOS