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]; }