Effective Objective-C 2.0 编写高质量iOS与OS X代码 理解消息转发机制
+ (BOOL)resolveInstanceMethod:(SEL)selector id autoDictionaryGetter(id self, SEL _cmd); void autoDictionarySetter(id self, SEL _cmd, id value); + (BOOL)resolveInstanceMethod:(SEL)selector { NSString *selectorString = NSStringFromSelector(selector); if (/* selector is from a @dynamic property */) { if([selectorString hasPrefix:@“set”]) { class_addMethod(self, selector, (IMP)autoDictionarySetter, “v@:@“); }else { class_addMethod(self, selector, (IMP)autoDictionaryGetter, “@@:“); } return YES; } return [super resolveInstanceMethod:selector]; }
@interface EOCAutoDictionary : NSObject @property (nonatomic, strong) NSString *string; @property (nonatomic, strong) NSNumber *number; @property (nonatomic, strong) NSDate *date; @property (nonatomic, strong) id opaqueObject; @property (nonatomic, strong) NSMutableDictionary *backingStore; @end @interface EOCAutoDictionary @dynamic string, number, date, opaqueObject; - (id)init { if((self = [super init])){ _backingStore = [NSMutableDictionary new]; } return self; } + (BOOL)resolveInstanceMethod:(SEL)selector { NSString *selectorString = NSStringFromSelector(selector); if([selectorString hasPrefix:@“set”]) { class_addMethod(self, selector, (IMP)autoDictionarySetter, “v@:@“); }else { class_addMethod(self, selector, (IMP)autoDictionaryGetter, “@@:“); } return YES; } @end
id autoDictionaryGetter (id self, SEL _cmd) { // Get the backing store from the object EOCAutoDictionary *typedSelf = (EOCAutoDictionary*)self; NSMutableDictionary *backingStore = typedSelf.backingStore; // The key is simply the selector name NSString *key = NSStringFromSelector(_cmd); // Return the value return [backingStore objectForKey:key]; }
void autoDictionarySetter(id self,SEL _cmd, id value) { // Get the backing store from the object; EOCAutoDictionary *typedSelf = (EOCAutoDictionary*)self; NSMutableDictionary *backingStore = typedSelf.backingStore; // for “ :setOpaqueObject:” tobe “opaqueObject” NSString *selectorString = NSStringFromSelector(_cmd); NSMutableString *key = [selectorString mutableCopy]; [key deleteCharactersInRange:NSMakeRange(key.length - 1, 1)]; [key deleteCharactersInRange:NSMakeRange(0, 3)]; NSString 8lowercaseFistChar = [[key substringToIndex:1] lowercaseString]; [key replaceCharactersInRange:NSMakeRange(0,1) withString:lowercaseFirstChar]; if(value) [backingStore setObject:value forKey:key]; else [backingStore removeObjectForKey:key]; }
Effective Objective-C 2.0 编写高质量iOS与OS X代码 理解消息转发机制,,5-wow.com
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。