Why does objc_msgSend call EXC_BAD_ACCESS?

I created a class that has a specified objecttarget, a selectorto view, and displayTitledisplays a string in this format: @"displayTitle: object.selector". Then it registers through KVO, so that at any time valueof of it object.selectorchanges, it can notify the view controller to update the view. I use this as an abstract and reusable way to show a description of the various properties of an object to the user.

When I try to get the value object.selector, I cannot do [object performSelector:selector]it because LLVM gives errors when you use performSelector with a dynamic selector . So, I did exactly what this answer suggested: I used objc_msgSend(object, selector).

- (instancetype)initWithSelector:(SEL)selector onObject:(NSObject*)object displayTitle:(NSString*)displayTitle {
    self = [super init];

    if (self) {
        id value;

        if ([object respondsToSelector:selector) {
            // Used objc_msgSend instead of performSelector to suppress a LLVM warning which was caused by using a dynamic selector.
            value = objc_msgSend(object, selector);
        } else {
            return nil;
        }

        [self setItemDescription:[NSString stringWithFormat:@"%@: %@", displayTitle, value]];
    }

    return self;
}

And I got it EXC_BAD_ACCESS!

Screen shot

, , [object selector].

, ?

+4
3

objc_msgSend id, ARC ( objc_retain, ), isnt , 8, objc_retain . , EXC_BAD_ACCESS.

value NSUInteger ( -). , selector . , ( nil), ARC.

+3

, 8, Integer?

, , .. 0x8, , EXC_BAD_ACCESS, 0x8 .

, NSNumber

+3

C, Objective-C, .

When you use the objc_msgSendfunctions associated with it, before you call it, you need to specify it with the correct type of function pointer. From other answers and comments, it seems that your method accepts no parameters and has a return type NSInteger. In this case, to use it, you should do something like:

NSInteger value;
NSInteger (*f)(id, SEL) = (NSInteger (*)(id, SEL))objc_msgSend;
value = f(object, selector);
+3
source

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


All Articles