Rob Sanders
Rob Sanders

Reputation: 5347

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.

Upvotes: 0

Views: 591

Answers (2)

newacct
newacct

Reputation: 122419

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);

Upvotes: 1

matt
matt

Reputation: 534885

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

My advice, then, would be to suppress the warnings and just call performSelector:....

Upvotes: 0

Related Questions