保存对象的不同状态值
保存对象的不同状态值
效果
说明
1. 存储不同的状态,对于一个对象而言还是很有必要的,尤其是需要频繁切换状态的时候.
2. block是对象,是可以存储在集合中的.
源码
https://github.com/YouXianMing/ViewState
// // NSObject+StatePattern.h // ViewState // // Created by YouXianMing on 15/6/30. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import <Foundation/Foundation.h> typedef void(^NSObjectBlock_t)(id object); @interface NSObject (StatePattern) /** * 存储状态的字典 */ @property (nonatomic, strong, readonly) NSMutableDictionary *stateDictionary; /** * 注册状态 * * @param stateString 状态标签值 * @param stateBlock 保存状态的block */ - (void)registerState:(NSString *)stateString stateBlock:(NSObjectBlock_t)stateBlock; /** * 切换到指定标签的状态 * * @param stateString 状态标签值 */ - (void)switchToState:(NSString *)stateString; @end
// // NSObject+StatePattern.m // ViewState // // Created by YouXianMing on 15/6/30. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import "NSObject+StatePattern.h" #import <objc/runtime.h> @implementation NSObject (StatePattern) - (void)registerState:(NSString *)stateString stateBlock:(NSObjectBlock_t)stateBlock { [self setup]; [self.stateDictionary setObject:stateBlock forKey:stateString]; } - (void)switchToState:(NSString *)stateString { [self setup]; NSObjectBlock_t block = [self.stateDictionary objectForKey:stateString]; if (block) { __weak id weakSelf = self; block(weakSelf); } } - (void)setup { if (self.stateDictionary == nil) { self.stateDictionary = [NSMutableDictionary dictionary]; } } #pragma mark - runtime属性 @dynamic stateDictionary; NSString * const _recognizerStateDictionary = @"_recognizerStateDictionary"; - (void)setStateDictionary:(NSMutableDictionary *)stateDictionary { objc_setAssociatedObject(self, (__bridge const void *)(_recognizerStateDictionary), stateDictionary, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (NSMutableDictionary *)stateDictionary { return objc_getAssociatedObject(self, (__bridge const void *)(_recognizerStateDictionary)); } @end
注意