zoukankan      html  css  js  c++  java
  • [IOS Block和delegate的对比]

    原文:http://blog.sina.com.cn/s/blog_9e8867eb0102uykn.html

    这篇文章建议和前一篇一起看, 另外先弄清楚IOS的block是神马东东。

    委托和block是IOS上实现回调的两种机制。Block基本可以代替委托的功能,而且实现起来比较简洁,比较推荐能用block的地方不要用委托。

    本篇的demo和前一篇是同一个,可以到github上下载不同的版本, 源码下载地址:

    https://github.com/pony-maggie/DelegateDemo

    A类(timeControl类)的头文件先要定义block,代码如下:

    //委托的协议定义
    @protocol UpdateAlertDelegate <NSObject>
    - (void)updateAlert;
    @end
    
    
    
    @interface TimerControl : NSObject
    //委托变量定义
    @property (nonatomic, weak) id<UpdateAlertDelegate> delegate;
    
    
    //block
    typedef void (^UpdateAlertBlock)();
    @property (nonatomic, copy) UpdateAlertBlock updateAlertBlock;
    
    - (void) startTheTimer;
       
    @end

    A类的实现文件,原来用委托的地方改成调用block:

     
    - (void) timerProc
    {
        //[self.delegate updateAlert];//委托更新UI
        //block代替委托
        if (self.updateAlertBlock)
        {
            self.updateAlertBlock();
        }
    }

    再来看看视图类,实现block即可:

     
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        TimerControl *timer = [[TimerControl alloc] init];
        timer.delegate = self; //设置委托实例
        
        //实现block
        timer.updateAlertBlock = ^()
        {
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"时间到" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
            
            alert.alertViewStyle=UIAlertViewStyleDefault;
            [alert show];
        };
        
        
        
        [timer startTheTimer];//启动定时器,定时5触发
    }
  • 相关阅读:
    8款超酷体验的jQuery/CSS3应用插件
    6款基于SVG的HTML5CSS3应用和动画
    精妙无比 8款HTML5动画实例及源码
    超赞值得一试的六款jQuery插件和CSS3应用
    不容错过的七个jQuery图片滑块插件
    7款值得你心动的HTML5动画和游戏
    8款HTML5动画特效推荐源码
    绝对震撼 7款HTML5动画应用及源码
    8款超酷而实用的CSS3按钮动画
    10款强大的jQuery/HTML5应用新鲜出炉
  • 原文地址:https://www.cnblogs.com/rayshen/p/3968655.html
Copyright © 2011-2022 走看看