Objective-C学习之路 委托用法与讲解
Objective-C学习之路 委托用法与讲解,是本文要介绍的内容,当然在学习委托之前,你也许对Objective-C已经很是了解了,那么我们直接看内容。
(1)雇主与委托者共同参与一个处理,说白了就是调用雇主方法的时候在雇主的方法内不但有相应的逻辑处理,还得请求委托者的方法共同处理
(2)请求委托者的方法时要将自己传递过去,也就是说把自己当作一个入参传递过去,当然也可以有不同的实现,只是委托者能获得雇主就可以
#import <Cocoa/Cocoa.h> /** *委托的Demo * *@author 肖浩 **/ //委托类,委托类没有任何方法声明,它只需实现非正规协议的中需要的方法 @interface DemoDelegate : NSObject @end //DemoDelegate //雇主类 @interface Demo : NSObject { //委托类 DemoDelegate *demoDelegate; } -(void) setDemoDelegate : (DemoDelegate *) delegate; -(void) sendMessage; @end //Demo //NSObject的WSDelegate类别,定义非正规协议 @interface NSObject (WSDelegate) -(void) setDemoDelegate : (DemoDelegate *) delegate; -(void) handlerDelegate : (Demo *) demo; @end //WSDelegate @implementation Demo -(void) setDemoDelegate : (DemoDelegate *) delegate { [delegate retain]; [demoDelegate release]; demoDelegate = delegate; } //通知委托类方法执行 -(void) sendMessage { [demoDelegate handlerDelegate : self]; } -(void) dealloc { [demoDelegate release]; [super dealloc]; } @end //Demo @implementation DemoDelegate //相应的委托方法 -(void) handlerDelegate : (Demo *) demo { NSLog(@"%@", demo); } @end //DemoDelegate int main (int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; Demo *demo = [[Demo alloc] init]; DemoDelegate *delegate = [[DemoDelegate alloc] init]; [demo setDemoDelegate : delegate]; [demo sendMessage]; [pool release]; return (0); }
相关推荐
fort0 2020-05-16
81570790 2020-04-16
86540698 2020-04-08
zhoutaifeng 2020-03-07
好好学习天天 2020-03-06
InterestSoul 2020-02-17
82467413 2019-12-31
84407518 2012-07-16
81570790 2013-07-01
83254851 2013-08-29
84334052 2019-11-19
86540698 2019-11-19
84467715 2011-07-25
81731290 2014-03-22
85437811 2014-03-22
dahuichen 2019-10-25
ObjectiveC 2011-09-20
80530297 2015-04-14
80530297 2015-04-20