测试已测试 | ✓ |
语言语言 | Obj-CObjective C |
许可证 | Apache 2 |
发布最新发布 | 2015年6月 |
由 Blake Watters,Blake Watters 维护。
Objective-C 中实现状态机的简单、优雅的基于块的 API
TransitionKit 是一个小型 Cocoa 库,它提供了一种在 Objective-C 中实现状态机的 API。它功能齐全、文档完整、单元测试彻底。状态机是管理应用程序复杂性的好方法,TransitionKit 提供了优雅的 API,以便在您的下一个 iOS 或 Mac OS X 应用程序中实现状态机。
userInfo
字典包含任意用户数据,便于在回调中广播元数据。以下是一个简单的状态机示例,用于模拟收件箱中消息的状态。
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 使用 Kiwi BDD 库进行测试。为了运行测试,您必须执行以下操作
pod install
open TransitionKit.xcworkspace
Blake Watters
TransitionKit 在 Apache 2 许可证下提供。有关更多信息,请参阅 LICENSE 文件。