Duck
Duck

Reputation: 36013

Running a bunch of methods by string and receiving a value

I have a bunch of methods that return a bool value. These are tests that check for n conditions. If one of them returns YES, the condition is invalid. Something like

- (BOOL) areNumbersInvalid {

}

- (BOOL) areNumbersBigger {

}

// etc...

There are hundreds of methods.

Actually I would run them like this:

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

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

// etc

Imagine hundreds of lines like this for every method.

Than I thought I could have all method names on an array and use something like

  [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
                              }


                            }];

but I cannot use this line

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

because this performSelector line expects a void return will not return a BOOL value

How do I do this?

Upvotes: 0

Views: 69

Answers (3)

Bryan Chen
Bryan Chen

Reputation: 46608

If you know the method signature at compile time (BOOL (*)(id, SEL) in this case), you can do this

SEL selector = // ...
id obj = // ...
BOOL (*imp)(id, SEL);
imp = (BOOL (*)(id, SEL))[obj methodForSelector:selector];
BOOL result = imp(obj, selector); // call it

less overhead compare to NSInvocation

Upvotes: 0

Tiago Almeida
Tiago Almeida

Reputation: 14237

I believe 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");

Upvotes: 3

santhu
santhu

Reputation: 4792

create a class property as

@property BOOL failed;

In those methods, update the failed property accordingly.
And after executing

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

check for failed.

Upvotes: 0

Related Questions