状态机

状态机

#import 
@property (nonatomic, strong) TKStateMachine *stateMachine;

static NSString * const kLoading = @"kLoading";
static NSString * const kPlaying = @"kPlaying";
static NSString * const kPause = @"kPause";
static NSString * const kFinish = @"kFinish";
    self.stateMachine = [[TKStateMachine alloc] init];
    
    ///加载中 状态
    TKState *loading = [TKState stateWithName:kLoading];
    [loading setDidEnterStateBlock:^(TKState *state, TKTransition *transition) {
        /// TODO
        NSLog(@"-----------------------");
        NSLog(@"loading - 1");
    }];
    ///播放状态
    TKState *playing = [TKState stateWithName:kPlaying];
    ///进入该状态
    [playing setDidEnterStateBlock:^(TKState *state, TKTransition *transition) {
        /// TODO
        NSLog(@"-----------------------");
        NSLog(@"playing - 1");
    }];
    ///离开该状态
    [playing setDidExitStateBlock:^(TKState *state, TKTransition *transition) {
        /// TODO
        NSLog(@"-----------------------");
        NSLog(@"playing - 2");
    }];
    
    ///暂停状态
    TKState *pause = [TKState stateWithName:kPause];
    [pause setDidEnterStateBlock:^(TKState *state, TKTransition *transition) {
        /// TODO
        NSLog(@"-----------------------");
        NSLog(@"pause - 1");
    }];
    ///播放完成状态
    TKState *finish = [TKState stateWithName:kFinish];
    [finish setDidEnterStateBlock:^(TKState *state, TKTransition *transition) {
        /// TODO
        NSLog(@"-----------------------");
        NSLog(@"finish - 1");
    }];
    ///添加所有状态
    [self.stateMachine addStates:@[loading, playing, pause, finish]];
    ///初始状态
    [self.stateMachine setInitialState:finish];
    
    ///关联事件
    TKEvent *loadingEvent = [TKEvent eventWithName:loading.name transitioningFromStates:@[playing, pause, finish] toState:loading];
    TKEvent *playingEvent = [TKEvent eventWithName:kPlaying transitioningFromStates:@[loading, pause, finish] toState:playing];
    TKEvent *pauseEvent = [TKEvent eventWithName:kPause transitioningFromStates:@[playing, loading] toState:pause];
    TKEvent *finishEvent = [TKEvent eventWithName:kFinish transitioningFromStates:@[loading, playing, pause] toState:finish];
    
    ///添加事件
    [_stateMachine addEvents:@[loadingEvent, playingEvent, pauseEvent, finishEvent]];
    ///激活
    [_stateMachine activate];

BOOL can = [self.stateMachine canFireEvent:kLoading];
[self.stateMachine fireEvent:kLoading userInfo:nil error:nil];

你可能感兴趣的:(状态机)