美文网首页
iOS 调用performSelector 时的警告问题

iOS 调用performSelector 时的警告问题

作者: 小海豚丶 | 来源:发表于2021-10-13 10:20 被阅读0次

在调用performSelector的时候Xcode总是会多出一条警告,看着就别扭

performSelector may cause a leak because its selector is unknown

那么怎么解决呢?

1、宏编译忽略它

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
     [self performSelector:@selector(methodName) withObject:parameter];
#pragma clang diagnostic pop

2、推荐做法,分四种情况,写法一看便明白了

/// 无参无返回值
SEL selector = NSSelectorFromString(@"method");
IMP imp = [object methodForSelector:selector];
void (*func)(id, SEL) = (void *)imp;
func(object, selector);

/// 有参有返回值
SEL selector = NSSelectorFromString(@"method: parameter1: parameter2");
IMP imp = [object methodForSelector:selector];
CGRect (*func)(id, SEL, CGRect, UIView *) = (void *)imp;
CGRect result = func(object, selector, p1, p2); 

/// 有参无返回值
SEL selector = NSSelectorFromString(@"method: parameter1");
IMP imp = [object methodForSelector:selector];
void (*func)(id, SEL, CGFloat) = (void *)imp;
func(object, selector, p1);

/// 无参有返回值
SEL selector = NSSelectorFromString(@"method");
IMP imp = [object methodForSelector:selector];
BOOL (*func)(id, SEL) = (void *)imp;
BOOL result = func(object, selector); 

相关文章

网友评论

      本文标题:iOS 调用performSelector 时的警告问题

      本文链接:https://www.haomeiwen.com/subject/jcusoltx.html