regetskcob
regetskcob

Reputation: 1192

PerformSelector may cause a leak - Better solution

I have a custom BackBarButton where I have a property to store a selector which can change in some cases. So I can't use delegation really smoothly.

Warning description

What can I do to get rid of this warning without changing the 'workflow' to delegation? The property is defined by using this:

@property (nonatomic, strong) id<SPUniversalBackBarButtonItemDelegate> delegate;
@property (nonatomic, assign) SEL delegationSelector;

I also tried to use this code, but it says 'No known instance method for selector...' and 'Implicit conversation of an Objective-C pointer to IMP'...

IMP imp = [[self delegate] methodForSelector:[self delegationSelector]];
void (*func)(id, SEL) = (void *)imp;
func([self delegate], [self delegationSelector]);

Upvotes: 1

Views: 3604

Answers (2)

Tiago Almeida
Tiago Almeida

Reputation: 14237

First why is your delegate strong? I really doubt you want a strong delegate. Most of the times you want a weak delegate because you don't want your object to dictate the memory status of your delegate.

An alternative to perform selector is NSInvocation:

NSMethodSignature * mySignature = [self.delegate methodSignatureForSelector:self.delegationSelector];
NSInvocation * myInvocation = [NSInvocation
invocationWithMethodSignature:mySignature];
myInvocation.target = self.delegate;
myInvocation.selector = self.delegationSelector;
[myInvocation invoke];

Upvotes: 4

wolffan
wolffan

Reputation: 1104

You can expose your method in the protocol declaration. Then you will be able to call it without the need of a selector. And you won't have that warning.

OR

if you just want to get rid of the warning:

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        //code here will ignore the warning
#pragma clang diagnostic pop

Upvotes: 6

Related Questions