objc與鴨子對象(上)
分析"objc與鴨子對象"代碼,該作者使用protocol實現(xiàn)一個模型的協(xié)議,使用NSProxy代理實現(xiàn)模型的存取值,十分巧妙,下面注釋慢慢分析
XXUserEntity.h
//
// XXUserEntity.h
// XXDuckDemo
//
// Created by sunnyxx on 14-8-27.
// Copyright (c) 2014年 sunnyxx. All rights reserved.
//
// 無需實體類,只需要協(xié)議
@protocol XXUserEntity <NSObject>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *sex;
@property (nonatomic, strong) NSNumber *age; // 要用基本類型需要實現(xiàn)自動拆裝箱
@end
XXDuckEntity.h
//
// XXDuckEntity.h
// XXDuckDemo
//
// Created by sunnyxx on 14-8-16.
// Copyright (c) 2014年 sunnyxx. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol XXDuckEntity <NSObject>
@property (nonatomic, copy, readonly) NSString *jsonString;
@end
extern id/*<XXDuckEntity>*/ XXDuckEntityCreateWithJSON(NSString *json);
XXDuckEntity.m
//
// XXDuckEntity.m
// XXDuckDemo
//
// Created by sunnyxx on 14-8-16.
// Copyright (c) 2014年 sunnyxx. All rights reserved.
//
#import "XXDuckEntity.h"
@interface XXDuckEntity : NSProxy <XXDuckEntity>
//將jsonString轉(zhuǎn)成的字典,下面的消息轉(zhuǎn)發(fā)會將setter和getter映射到這個字典!!十分關(guān)鍵的一個屬性
@property (nonatomic, strong) NSMutableDictionary *innerDictionary;
@end
@implementation XXDuckEntity
//實現(xiàn)XXDuckEntity協(xié)議里的熟悉
@synthesize jsonString = _jsonString;
- (instancetype)initWithJSONString:(NSString *)json
{
if (json) {
self->_jsonString = [json copy];
NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding];
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
if ([jsonObject isKindOfClass:[NSDictionary class]]) {
self.innerDictionary = [jsonObject mutableCopy];
}
return self;
}
return nil;
}
#pragma mark - Message Forwading
//消息轉(zhuǎn)發(fā)流程 先methodSignatureForSelector:后forwardInvocation:,methodSignatureForSelector生成的簽名會生成下面forwardInvocation的invocation
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
// Change method signature to NSMutableDictionary's
// getter -> objectForKey:
// setter -> setObject:forKey:
SEL changedSelector = aSelector;
/*
為本類的用法,XXUserEntity作為一個協(xié)議其實只是騙過編譯器而不報警告
NSString *json = @"{\"name\": \"sunnyxx\", \"sex\": \"boy\", \"age\": 24}";
id<XXDuckEntity, XXUserEntity> entity= XXDuckEntityCreateWithJSON(json);
*/
//將setter和getter映射到字典
if ([self propertyNameScanFromGetterSelector:aSelector]) {
changedSelector = @selector(objectForKey:);
}
else if ([self propertyNameScanFromSetterSelector:aSelector]) {
changedSelector = @selector(setObject:forKey:);
}
NSMethodSignature *sign = [[self.innerDictionary class] instanceMethodSignatureForSelector:changedSelector];
return sign;
}
//NSInvocation是方法的封裝,可以對方法參數(shù)設(shè)值
- (void)forwardInvocation:(NSInvocation *)invocation
{
NSString *propertyName = nil;
// Try getter
propertyName = [self propertyNameScanFromGetterSelector:invocation.selector];
if (propertyName) {
invocation.selector = @selector(objectForKey:);
[invocation setArgument:&propertyName atIndex:2]; // self, _cmd, key
[invocation invokeWithTarget:self.innerDictionary];
return;
}
// Try setter
propertyName = [self propertyNameScanFromSetterSelector:invocation.selector];
if (propertyName) {
invocation.selector = @selector(setObject:forKey:);
[invocation setArgument:&propertyName atIndex:3]; // self, _cmd, obj, key
[invocation invokeWithTarget:self.innerDictionary];
return;
}
[super forwardInvocation:invocation];
}
#pragma mark - Helpers
- (NSString *)propertyNameScanFromGetterSelector:(SEL)selector
{
NSString *selectorName = NSStringFromSelector(selector);
NSUInteger parameterCount = [[selectorName componentsSeparatedByString:@":"] count] - 1;
if (parameterCount == 0) {
return selectorName;
}
return nil;
}
- (NSString *)propertyNameScanFromSetterSelector:(SEL)selector
{
NSString *selectorName = NSStringFromSelector(selector);
NSUInteger parameterCount = [[selectorName componentsSeparatedByString:@":"] count] - 1;
if ([selectorName hasPrefix:@"set"] && parameterCount == 1) {
NSUInteger firstColonLocation = [selectorName rangeOfString:@":"].location;
return [selectorName substringWithRange:NSMakeRange(3, firstColonLocation - 3)].lowercaseString;
}
return nil;
}
@end
id XXDuckEntityCreateWithJSON(NSString *json)
{
return [[XXDuckEntity alloc] initWithJSONString:json];
}
NSProxy——少見卻神奇的類,利用NSProxy實現(xiàn)多繼承
Smart Proxy Delegation,外國大神寫的NSProxy,用于簡化delegate的的實現(xiàn)