iOS之"performSelector may cause a leak because its selector is unknown"警告原因及其解決辦法

問題描述

原因

  • 在ARC模式下,運行時需要知道如何處理你正在調(diào)用的方法的返回值。這個返回值可以是任意值,如 voidint, char , NSString , id 等等。ARC通過頭文件的函數(shù)定義來得到這些信息。所以平時我們用到的靜態(tài)選擇器就不會出現(xiàn)這個警告。因為在編譯期間,這些信息都已經(jīng)確定。
    如:
...
[someController performSelector:@selector(someMethod)];
...
- (void)someMethod
{
  //bla bla...
}

而使用 [someController performSelector: NSSelectorFromString(@"someMethod")];時ARC并不知道該方法的返回值是什么,以及該如何處理?該忽略?還是標記為ns_returns_retained 還是 ns_returns_autoreleased ?

解決辦法

  • 1.使用函數(shù)指針方式
SEL selector = NSSelectorFromString(@"someMethod");
IMP imp = [_controller methodForSelector:selector];
void (*func)(id, SEL) = (void *)imp;
func(_controller, selector);

當有額外參數(shù)時:

SEL selector = NSSelectorFromString(@"processRegion:ofView:");
IMP imp = [_controller methodForSelector:selector];
CGRect (*func)(id, SEL, CGRect, UIView *) = (void *)imp;
CGRect result = func(_controller, selector, someRect, someView);
  • 2.使用宏忽略警告
#define SuppressPerformSelectorLeakWarning(Stuff) \
    do { \
        _Pragma("clang diagnostic push") \
        _Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
        Stuff; \
        _Pragma("clang diagnostic pop") \
    } while (0)

在產(chǎn)生警告也就是performSelector的地方用使用該宏

SuppressPerformSelectorLeakWarning(
    [_target performSelector:_action withObject:self]
);

如果需要 performSelector 返回值的話

id result;
SuppressPerformSelectorLeakWarning(
    result = [_target performSelector:_action withObject:self]
);
  • 3.使用afterDelay
[self performSelector:aSelector withObject:nil afterDelay:0.0];

如果在接受范圍內(nèi),允許在下一個runloop執(zhí)行,可以這么做。xCode5沒問題,但據(jù)反映,xcode6的話這個不能消除警告。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容