-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathFSMMachine.m
59 lines (44 loc) · 1.46 KB
/
FSMMachine.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#import "FSMMachine.h"
@interface FSMMachine()
@property (nonatomic, readwrite, strong) const NSString* state;
@property (nonatomic, strong) NSMutableDictionary* transitions;
@end
@implementation FSMMachine
@synthesize state = _state;
@synthesize transitions;
- (id)initWithState:(const NSString*)state {
self = [super init];
if (self) {
self.state = state;
self.transitions = [NSMutableDictionary dictionary];
}
return self;
}
- (void)addTransition:(const NSString*)event startState:(const NSString*)startState endState:(const NSString*)endState {
NSMutableDictionary* startEndMap = nil;
startEndMap = [self.transitions objectForKey:event];
if (!startEndMap) {
startEndMap = [NSMutableDictionary dictionary];
[self.transitions setObject:startEndMap forKey:event];
}
[startEndMap setObject:endState forKey:startState];
}
- (BOOL)applyEvent:(const NSString*)event {
BOOL valid = NO;
NSDictionary* startEndMap = [self.transitions objectForKey:event];
if (startEndMap) {
NSString* endState = [startEndMap objectForKey:self.state];
if (endState) {
self.state = endState;
valid = YES;
}
}
if (!valid) {
NSLog(@"WARNING! Tried to appy event %@ while in state %@.", event, self.state);
}
return valid;
}
- (BOOL)isInState:(const NSString *)state {
return self.state == state;
}
@end