NSProxy

objc与鸭子对象(上)
分析"objc与鸭子对象"代码,该作者使用protocol实现一个模型的协议,使用NSProxy代理实现模型的存取值,十分巧妙,下面注释慢慢分析
XXUserEntity.h

//
//  XXUserEntity.h
//  XXDuckDemo
//
//  Created by sunnyxx on 14-8-27.
//  Copyright (c) 2014年 sunnyxx. All rights reserved.
//

// 无需实体类,只需要协议
@protocol XXUserEntity 
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *sex;
@property (nonatomic, strong) NSNumber *age; // 要用基本类型需要实现自动拆装箱
@end

XXDuckEntity.h

//
//  XXDuckEntity.h
//  XXDuckDemo
//
//  Created by sunnyxx on 14-8-16.
//  Copyright (c) 2014年 sunnyxx. All rights reserved.
//

#import 

@protocol XXDuckEntity 
@property (nonatomic, copy, readonly) NSString *jsonString;
@end

extern id/**/ 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 
//将jsonString转成的字典,下面的消息转发会将setter和getter映射到这个字典!!十分关键的一个属性
@property (nonatomic, strong) NSMutableDictionary *innerDictionary;
@end

@implementation XXDuckEntity
//实现XXDuckEntity协议里的熟悉
@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
//消息转发流程 先methodSignatureForSelector:后forwardInvocation:,methodSignatureForSelector生成的签名会生成下面forwardInvocation的invocation

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    // Change method signature to NSMutableDictionary's
    // getter -> objectForKey:
    // setter -> setObject:forKey:

    SEL changedSelector = aSelector;
    /*
     为本类的用法,XXUserEntity作为一个协议其实只是骗过编译器而不报警告
     NSString *json = @"{\"name\": \"sunnyxx\", \"sex\": \"boy\", \"age\": 24}";
     id 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是方法的封装,可以对方法参数设值
- (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实现多继承
Smart Proxy Delegation,外国大神写的NSProxy,用于简化delegate的的实现

你可能感兴趣的:(NSProxy)