ios - 通过字符串运行一堆方法并接收一个值

标签 ios iphone ipad cocoa-touch

我有一堆返回 bool 值的方法。这些是检查 n 个条件的测试。如果其中之一返回 YES,则条件无效。有点像

- (BOOL) areNumbersInvalid {

}

- (BOOL) areNumbersBigger {

}

// etc...

有数百种方法。

实际上我会这样运行它们:

if ([self areNumbersInvalid]) {
   [self failed];
}

if ([self areNumbersBigger]) {
   [self failed];
}

// etc

想象一下,每种方法都有数百行这样的代码。

我以为我可以将所有方法名称放在一个数组上并使用类似的东西

  [methods enumerateObjectsWithOptions:NSEnumerationConcurrent
                            usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

                              NSString *oneMethod = (NSString *)obj;
                              SEL selector = NSSelectorFromString(oneMethod);

                              BOOL failed = [self  performSelector:selector withObject:nil afterDelay:0.0f];

                              if (failed) {
                                // do something
                              }


                            }];

但是我不能使用这条线

BOOL failed = [self  performSelector:selector withObject:nil afterDelay:0.0f];

因为此 performSelector 行期望 void return 不会返回 BOOL 值

我该怎么做?

最佳答案

我相信you can use NSInvocation for that :

NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
                            [[someInstance class] instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:someInstance];
[invocation invoke];
BOOL returnValue;
[invocation getReturnValue:&returnValue];
NSLog(@"Returned %@", returnValue? @"YES" : @"NO");

关于ios - 通过字符串运行一堆方法并接收一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21241798/

相关文章:

iphone - iOS 4 上的 CALayer 或 UIView backgroundColor UIImage

javascript - Yahoo yui 和 iPad 定位

javascript - 两个 amCharts 图表未在 iPad 上使用 jQueryMobile 框架显示在同一页面上

ios - swift 错误 : Value of type 'NSObject -> () ' AnimalListTableViewController' has no member 'tableView'

ios - 如何在 swift (IOS 8) 中连接蓝牙设备 (OBDII) 并发送/接收数据?

ios - 错误消息: Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeead03e18)

ios - 在 Swift 中为 NSDateComponenstFormatter 设置多个 allowedUnits

iphone - Cocos2d for iPhone 与 Cocos2d-x

ios - 如何找到 NSMutableArray 索引

ipad - iOS5文件共享: recognize when files have been added to a Directory?