TestsTested | ✓ |
LangLanguage | Obj-CObjective C |
License | Apache 2 |
ReleasedLast Release | Jun 2015 |
Maintained by Blake Watters, Blake Watters.
A simple, elegantly designed block based API for implementing State Machines in Objective-C
TransitionKit is a small Cocoa library that provides an API for implementing a state machine in Objective C. It is full-featured, completely documented, and very thoroughly unit tested. State machines are a great way to manage complexity in your application and TransitionKit provides you with an elegant API for implementing state machines in your next iOS or Mac OS X application.
userInfo
dictionary, making it easy to broadcast metadata across callbacks.The following example is a simple state machine that models the state of a Message in an Inbox.
TKStateMachine *inboxStateMachine = [TKStateMachine new];
TKState *unread = [TKState stateWithName:@"Unread"];
[unread setDidEnterStateBlock:^(TKState *state, TKTransition *transition) {
[self incrementUnreadCount];
}];
TKState *read = [TKState stateWithName:@"Read"];
[read setDidExitStateBlock:^(TKState *state, TKTransition *transition) {
[self decrementUnreadCount];
}];
TKState *deleted = [TKState stateWithName:@"Deleted"];
[deleted setDidEnterStateBlock:^(TKState *state, TKTransition *transition) {
[self moveMessageToTrash];
}];
[inboxStateMachine addStates:@[ unread, read, deleted ]];
inboxStateMachine.initialState = unread;
TKEvent *viewMessage = [TKEvent eventWithName:@"View Message" transitioningFromStates:@[ unread ] toState:read];
TKEvent *deleteMessage = [TKEvent eventWithName:@"Delete Message" transitioningFromStates:@[ read, unread ] toState:deleted];
TKEvent *markAsUnread = [TKEvent eventWithName:@"Mark as Unread" transitioningFromStates:@[ read, deleted ] toState:unread];
[inboxStateMachine addEvents:@[ viewMessage, deleteMessage, markAsUnread ]];
// Activate the state machine
[inboxStateMachine activate];
[inboxStateMachine isInState:@"Unread"]; // YES, the initial state
// Fire some events
NSDictionary *userInfo = nil;
NSError *error = nil;
BOOL success = [inboxStateMachine fireEvent:@"View Message" userInfo:userInfo error:&error]; // YES
success = [inboxStateMachine fireEvent:@"Delete Message" userInfo:userInfo error:&error]; // YES
success = [inboxStateMachine fireEvent:@"Mark as Unread" userInfo:userInfo error:&error]; // YES
success = [inboxStateMachine canFireEvent:@"Mark as Unread"]; // NO
// Error. Cannot mark an Unread message as Unread
success = [inboxStateMachine fireEvent:@"Mark as Unread" userInfo:nil error:&error]; // NO
// error is an TKInvalidTransitionError with a descriptive error message and failure reason
TransitionKit is tested using the Kiwi BDD library. In order to run the tests, you must do the following:
pod install
open TransitionKit.xcworkspace
Blake Watters
TransitionKit is available under the Apache 2 License. See the LICENSE file for more info.