简体   繁体   中英

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.

警告说明

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM