我在类设置中放了很多@dynamic类型变量,方便setXxx和xxx(get方法),我使用object-C运行时功能批量处理它们,请参阅下面的代码。
它运行良好,但是当我进行逻辑单元测试时,我需要模拟这个类,然后抛出异常,它找不到@dynamic的set和get方法,所以我只能实现set和get方法测试目标中的每个@dynamic都可以解决它。
我的问题是为什么object-c运行时功能在我的测试目标中不起作用?如果我做一些代码更改,是否可以使它工作?
任何想法或讨论都将受到赞赏,在此先感谢。
@dynamic preferencesGeneralRegion;
@dynamic preferencesGeneralUnits;
@dynamic ...
...
- (NSMethodSignature*)methodSignatureForSelector:(SEL)aSelector
{
if([NSStringFromSelector(aSelector) hasPrefix:@"set"])
{
return [NSMethodSignature signatureWithObjCTypes:"v@:@"];
}
return [NSMethodSignature signatureWithObjCTypes:"@@:"];
}
- (void)forwardInvocation:(NSInvocation*) anInvocation
{
NSString *selector = NSStringFromSelector(anInvocation.selector);
if([selector hasPrefix:@"set"])
{
NSRange firstChar, rest;
firstChar.location = 3;
firstChar.length = 1;
rest.location = 4;
rest.length = selector.length - 5;
selector = [NSString stringWithFormat:@"%@%@",
[[selector substringWithRange:firstChar] lowercaseString],
[selector substringWithRange:rest]];
id value;
[anInvocation getArgument:&value atIndex:2];
[[NSUserDefaults standardUserDefaults] setObject:value forKey:selector];
[[NSUserDefaults standardUserDefaults] synchronize];
}
else
{
selector = [NSString stringWithFormat:@"%@", selector];
id value = [[NSUserDefaults standardUserDefaults] objectForKey:selector];
[anInvocation setReturnValue:&value];
}
}