zoukankan      html  css  js  c++  java
  • ios delegate 和 block

    //委托的协议定义
    @protocol UpdateDelegate <NSObject>
    - (void)update;
    @end
    
    
    
    @interface Test : NSObject
    //委托变量定义
    @property (nonatomic, weak) id<UpdateDelegate> delegate;
    
    
    //block
    typedef void (^UpdateBlock)(id obj);
    @property (nonatomic, copy) UpdateBlock updateBlock;
    
    - (void) startTest;
       
    @end
    
    @implementation Test
    
    
    - (void) startTest
    {
    
        [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(scheduledEnd) userInfo:nil repeats:NO];
    }
    
    - (void)scheduledEnd
    {
        [self.delegate update];//委托
        
        //block
        if (self.updateBlock)
        {
            self.updateBlock(@"test");
        }
    }
    
    @end
    
    
    // 实现
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        Test *test = [[Test alloc] init];
        test.delegate = self; //设置委托实例
        
        //实现block
        test.updateBlock = ^(id obj)
        {
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:obj delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
            
            alert.alertViewStyle=UIAlertViewStyleDefault;
            [alert show];
        };
    
        
        [test startTest];//启动定时器
    }
    
    //"被委托对象"实现协议声明的方法,由"委托对象"调用
    - (void)update
    {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"时间到" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
        
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
    }
  • 相关阅读:
    架构设计-业务逻辑层简述
    大牛的法宝
    架构设计中服务层的简单理解
    架构师都要懂哪些知识
    python 面向对象
    Ubuntu学习
    装饰器
    Py之基础数据类型
    Py之模块
    浏览器环境变量
  • 原文地址:https://www.cnblogs.com/joesen/p/4271605.html
Copyright © 2011-2022 走看看