Search code examples
objective-cswiftperformselector

Perform selector may cause a leak workaround swift crash


I have a situation where I want to call a method on a target where calling perform selector gives the error: PerformSelector may cause a leak because its selector is unknown.

To get round this I'm using the excellent solution from this SO question:

if (self.target) {
    IMP imp = [self.target methodForSelector:self.selector];
    void (*func)(id, SEL, id) = (void *)imp;
    func(self.target, self.selector, argument);
}

Now this code is part of a framework that I'm using in a Swift project and it's causing a crash.

If I ignore the warnings and use [self.target performSelector:self.selector withObject:self.argument]; It works fine.

So... I'm assuming this is to do with fundamental Swift vs. Objective-C message sending architecture. Please could someone tell me a) What's going on? b) how to get around it.


Solution

  • The most direct way to send the message (assuming it takes one object parameter and returns nothing) is:

    void (*func)(id, SEL, id) = (void (*)(id, SEL, id))objc_msgSend;
    func(self.target, self.selector, self.argument);