1.delegate
传值,传事件。
1、避免子类化带来的过多的子类以及子类与父类的耦合
2、通过委托传递消息机制实现分层解耦
eg.
代理
#import <Foundation/Foundation.h> @class Children; @protocol ChildrenDelegate <NSObject> @required - (void)Eat:(Children *)children; @optional //.... @end
代理对象->保姆
.h @interface 保姆 : NSObject<ChildrenDelegate> - (void)Eat:(Children *)children; @end .m @implementation 保姆 - (void)Eat:(Children *)children{ NSLog(@""); } @end
被代码对象->小孩
.h @interface Children : NSObject { id<ChildrenDelegate> delegate; NSInteger intTimer; } @property (strong) id<ChildrenDelegate> delegate; //-(void)setDelegate:(id)delegate; @end .m - (id)init { self=[super init]; if (self!=nil) { [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(go) userInfo:nil repeats:YES]; } return self; } - (void)go { [delegate Eat:self]; }
Test:
Children *c=[[Children alloc]init]; 保姆 *n=[[保姆 alloc]init]; c.delegate=n; // [c setDelegate:n]; [[NSRunLoop currentRunLoop]run];
时间: 2024-10-12 19:28:02