首页 > 移动平台 > 详细

ios delegate 和 block

时间:2015-02-04 10:37:44      阅读:316      评论:0      收藏:0      [点我收藏+]
//委托的协议定义
@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];
}

 

ios delegate 和 block

原文:http://www.cnblogs.com/joesen/p/4271605.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!