我在网上找到一份关于组件化的代码,里面有这样一段代码
- (id)performTarget:(NSString *)targetName action:(NSString *)actionName params:(NSDictionary *)params shouldCacheTarget:(BOOL)shouldCacheTarget
{
NSString *targetClassString = [NSString stringWithFormat:@"Target_%@", targetName];
NSString *actionString = [NSString stringWithFormat:@"Action_%@:", actionName];
id target = self.cachedTarget[targetClassString];
if (target == nil) {
Class targetClass = NSClassFromString(targetClassString);
target = [[targetClass alloc] init];
}
SEL action = NSSelectorFromString(actionString);
if (target == nil) {
// 这里是处理无响应请求的地方之一,这个demo做得比较简单,如果没有可以响应的target,就直接return了。实际开发过程中是可以事先给一个固定的target专门用于在这个时候顶上,然后处理这种请求的
return nil;
}
if (shouldCacheTarget) {
self.cachedTarget[targetClassString] = target;
}
if ([target respondsToSelector:action]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
return [target performSelector:action withObject:params];
#pragma clang diagnostic pop
} else {
// 这里是处理无响应请求的地方,如果无响应,则尝试调用对应target的notFound方法统一处理
SEL action = NSSelectorFromString(@"notFound:");
if ([target respondsToSelector:action]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
return [target performSelector:action withObject:params];
#pragma clang diagnostic pop
} else {
// 这里也是处理无响应请求的地方,在notFound都没有的时候,这个demo是直接return了。实际开发过程中,可以用前面提到的固定的target顶上的。
[self.cachedTarget removeObjectForKey:targetClassString];
return nil;
}
}
}
其中让我困惑的代码片段是这句话
return [target performSelector:action withObject:params];
我查看这段代码的定义,返回的是一个id值
- (id)performSelector:(SEL)aSelector withObject:(id)object;
真实运行代码的时候,也是返回了想要的结果,如截图
但是问题来了,我自己运行代码的时候,却一直崩溃,我的代码如下:
NSString *targetClassString = [NSString stringWithFormat:@"Test"];
NSString *actionString = [NSString stringWithFormat:@"t"];
Class targetClass = NSClassFromString(targetClassString);
id target = [[targetClass alloc] init];
SEL action = NSSelectorFromString(actionString);
if ([target respondsToSelector:action]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
id a = [target performSelector:action withObject:nil];
NSLog(@"%@",a);
#pragma clang diagnostic pop
}
截图:
请问我是哪里配置有问题吗,还是哪里出错了,我现在没有头绪,希望大神们能帮帮忙
Um...I know, the value of id a is the return value of the method you define. If it returns empty, the printing will crash