Selector cast

There really strange behavior happens using float / double / CGFloat when the performSelector function is executed:

Why does it work?

BOOL property = (BOOL)[self.object performSelector:@selector(boolProperty)];
NSInteger property = (NSInteger) [self.object performSelector:@selector(integerProperty)];

And it is not

CGFloat property = (CGFloat) [self.object performSelector:@selector(floatProperty)];

At first I tried to do this:

CGFloat property = [[self.object performSelector:@selector(floatProperty)] floatValue];

But in the end I got an EXC_BAD_ACCESS runtime error. I already figured out the hack to solve this problem, but I would like to understand why it works with Integer and Bool, and not with floating point types.

My hack:

@implementation NSObject (AddOn)
-(CGFloat)performFloatSelector:(SEL)aSelector
{
  NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:aSelector]];
  [invocation setSelector:aSelector];
  [invocation setTarget:self];
  [invocation invoke];
  CGFloat f = 0.0f;
  [invocation getReturnValue:&f];
  return f;
}
@end

Then:

CGFloat property = [self.object performFloatSelector:@selector(floatProperty)];
+4
source share
2 answers

The method performSelectoronly supports methods that do not return anything or an object. This is described in the documentation, which states:

, , , NSInvocation.

"" - , -.

, , , . performSelector id, . ; NSInteger, BOOL ; , . , id, , . , , , , () . - , , .

: , , performSelector ARC - , .

, . NSInvocation , , .

+4

NSInvocation, objc_msgSend ( , ):

BOOL (*f)(id, SEL) = (BOOL (*)(id, SEL))objc_msgSend;
BOOL property = f(self.object, @selector(boolProperty));

NSInteger (*f)(id, SEL) = (NSInteger (*)(id, SEL))objc_msgSend;
NSInteger property = f(self.object, @selector(integerProperty));

CGFloat (*f)(id, SEL) = (CGFloat (*)(id, SEL))objc_msgSend;
CGFloat property = f(self.object, @selector(floatProperty));

, , ; , 2 "" , self _cmd. , .

, struct objc_msgSend_stret objc_msgSend, , .

+1

Source: https://habr.com/ru/post/1542268/


All Articles