目标-动作机制

一对象发给另一对象的消息(动作),以此响应用户事件。

例如现有light,switch对象,通过查看switch状态来控制light开关。

 1 首先我们来了解两个虚拟的组件,开关和灯
 2 灯的声明文件
 3 @interface Light : NSObject
 4 
 5 -(void)turnOff; // 开灯
 6 -(void)turnOn; // 关灯
 7 
 8 @end
 9 可见灯的操作很简单,只有开灯和关灯两个方法。
10 开关的声明文件
11 typedef enum : NSUInteger {
12     SwitchStateOff, // default
13     SwitchStateOn,
14 } SwitchState;
15 
16 @interface Switch : NSObject
17 
18 @property(nonatomic,assign,readonly)SwitchState currentState;
19 
20 -(void)addChangeStateTarget:(id)target Action:(SEL)action;
21 
22 @end
23 开关有一个只读属性,为当前开关的状态,其状态变量为枚举类型
24 •    SwitchStateOff 表示关闭状态
25 •    SwitchStateOn 表示开启状态
26 开关还有一个addChangeStateTarget方法,通过该方法为这个开关设置反馈对象和反馈动作,以实现让反馈对象收到开关状态的改变信息。
27 下面我们假设有一个房间,房间中有一个开关和一个灯。代码实现如下:
28 @interface Room : NSObject
29 
30 @end
31 
32 @interface Room ()
33 
34 @property(nonatomic,strong) Light * aLight;
35 @property(nonatomic,strong) Switch * aSwitch;
36 
37 -(void)changeState:(Switch *)s;
38 
39 
40 @end
41 
42 @implementation Room
43 
44 - (instancetype)init
45 {
46     self = [super init];
47     if (self) 
48     {
49         self.aLight = [[Light alloc] init];
50         self.aSwitch = [[Switch alloc] init];
51         //设置反馈对象和反馈方法
52         [self.aSwitch addChangeStateTarget:self Action:@selector(changeState:)];
53     }
54     return self;
55 }
56 
57 -(void)changeState:(Switch *)s
58 {
59     if (self.aSwitch.currentState == SwitchStateOff)
60     {
61         [self.light turnOn];
62     }
63     else
64     {
65         [self.light turnOff];
66     }
67 }
68 
69 
70 @end

 

posted @ 2016-08-25 17:40  小二黑挖土  阅读(484)  评论(0编辑  收藏  举报