请原谅我的疯狂需求,但我正在编写的框架中创建了一堆仅基于属性的协议。
@protocol SomePropertiesOfAnObjectThing <NSObject>
@property (nonatomic, strong) NSString *larry;
@property (nonatomic, strong) NSString *curly;
@property (nonatomic, strong) NSString *moe;
@end
有没有一种方法,更重要的是一种简单的方法,可以“模拟”出实现此协议的对象?
id<SomePropertiesOfAnObjectThing> thingy = [ProtocolObject fromProtocol:@protocol(SomePropertiesOfAnObjectThing)];
thingy.larry = @"fizz";
thingy.curly = @"buzz";
thingy.moe = @"bar";
我想避免的两件事:
我会给任何可以给我展示干净便捷的方式(得票数至少为1)的人洗个澡。
我朴素的解决方案如下:
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
return [[self class] instanceMethodSignatureForSelector:@selector(foo:)];
}
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
NSString *argument;
[anInvocation getArgument:&argument atIndex:2];
if (argument) {
NSString *setterName = NSStringFromSelector(anInvocation.selector);
NSRange range = NSMakeRange(3, [setterName length]-4);
NSString *propertyName = [[setterName substringWithRange:range] lowercaseString];
[self performSelector:@selector(setFoo:value:) withObject:propertyName withObject:argument];
} else {
[self performSelector:@selector(foo:) withObject:argument];
}
}
- (id)foo:(id)key
{
return self.properties[key];
}
- (void)setFoo:(id)key value:(id)value
{
self.properties[key] = value;
}
- (id)valueForKey:(NSString *)key
{
return self.properties[key];
}
- (void)setValue:(id)value forKey:(NSString *)key
{
self.properties[key] = value;
}
稍后,当我针对值类型等进行优化时,我将使用更清洁的版本进行更新。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句