標籤:
//委託的協議定義@protocol UpdateDelegate <NSObject>- (void)update;@end@interface Test : NSObject//委託變數定義@property (nonatomic, weak) id<UpdateDelegate> delegate;//blocktypedef 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