重拾Effective Objective-C 2.0熱點問題

1. PerformSelector may cause a leak because its selector is unknown

原因是:在ARC模式下編譯器并不知道將要調(diào)用的選擇子是什么,因此,也就不能了解其方法簽名與返回值,甚至是否有返回值都不清楚(這個返回值可以是任意值,如 void , int , char , NSString , id 等)。而且,由于編譯器不知道方法名,所以就沒有運用ARC的內(nèi)存管理規(guī)則來判定是不是應該釋放。鑒于此,ARC采用比較謹慎的做法,就是不添加釋放操作。然而這么做可能造成內(nèi)存泄漏,因為方法返回對象可能將其保留了。
ARC通過頭文件的函數(shù)定義來得到這些信息。所以平時我們用到的靜態(tài)選擇器就不會出現(xiàn)這個警告。因為在編譯期間,這些信息都已經(jīng)確定。

截圖

而使用 [self performSelector:NSSelectorFromString(@"doSomething")]; 時ARC并不知道該方法的返回值是什么,以及該如何處理?該忽略?所以,ARC采用比較謹慎的做法,就是不添加釋放操作。

解決辦法

  • 使用函數(shù)指針方式
 SEL selector = NSSelectorFromString(@"doSomething");
 IMP imp = [self methodForSelector:selector];
 void (*func)(id, SEL) = (void *)imp;
 func(self, selector);
  • 使用宏定義忽略
_Pragma("clang diagnostic push")
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"")
 [self performSelector:NSSelectorFromString(@"doSomething")];
_Pragma("clang diagnostic pop")

2. 不要使用 dispatch_get_current_queue()

當然這個方法在iOS6.0就廢棄了,這里主要是重溫一下同步、異步以及死鎖。

- (NSString *)name
{
    __block NSString *name;
    dispatch_sync(_syncQueue, ^{
        name = @"some string";
    });
    return name;
}

上面的這種寫法可能會出現(xiàn)死鎖,假如調(diào)用獲取方法的隊列恰好是同步操作所在的隊列。那么dispatch_sync就會一直不返回,需要等待塊執(zhí)行完畢。
這里就想到使用dispatch_get_current_queue來解決問題。

- (NSString *)name
{
    __block NSString *name;
    void (^block)() = ^{
        name = @"iOS";
    };
    
    if (dispatch_get_current_queue() == _syncQueue) {
        block();
    }else {
        dispatch_sync(_syncQueue, block);
    }
    
    return name;
}

但是 dispatch_get_current_queue 仍然可能造成死鎖

  dispatch_sync(_syncQueueA, ^{
      dispatch_sync(_syncQueueB, ^{
          void (^block)() = ^{
            
          };
          if (dispatch_get_current_queue() == _syncQueueA) {
              block();
          }else {
              dispatch_sync(_syncQueueA, block);
          }
      });
   });

dispatch_get_current_queue 由于返回的是當前隊列,上面返回的是_syncQueueB。因此,針對_syncQueueA的同步派發(fā)依然會執(zhí)行,所以還是會造成死鎖。
其實要解決這個問題,可以使用隊列特有數(shù)據(jù) dispatch_queue_set_specific。只要去看源碼就會發(fā)現(xiàn) GPUImage(https://github.com/BradLarson/GPUImage) 等多數(shù)框架都是這么解決的。

static void *openGLESContextQueueKey;

- (id)init;
{
    if (!(self = [super init]))
    {
        return nil;
    }

    openGLESContextQueueKey = &openGLESContextQueueKey;
    _contextQueue = dispatch_queue_create("com.sunsetlakesoftware.GPUImage.openGLESContextQueue", GPUImageDefaultQueueAttribute());
    
#if OS_OBJECT_USE_OBJC
    dispatch_queue_set_specific(_contextQueue, openGLESContextQueueKey, (__bridge void *)self, NULL);
#endif
    shaderProgramCache = [[NSMutableDictionary alloc] init];
    shaderProgramUsageHistory = [[NSMutableArray alloc] init];
    
    return self;
}

void runSynchronouslyOnVideoProcessingQueue(void (^block)(void))
{
    dispatch_queue_t videoProcessingQueue = [GPUImageContext sharedContextQueue];
#if !OS_OBJECT_USE_OBJC
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    if (dispatch_get_current_queue() == videoProcessingQueue)
#pragma clang diagnostic pop
#else
    if (dispatch_get_specific([GPUImageContext contextKey]))
#endif
    {
        block();
    }else
    {
        dispatch_sync(videoProcessingQueue, block);
    }
}

void runAsynchronouslyOnVideoProcessingQueue(void (^block)(void))
{
    dispatch_queue_t videoProcessingQueue = [GPUImageContext sharedContextQueue];
    
#if !OS_OBJECT_USE_OBJC
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    if (dispatch_get_current_queue() == videoProcessingQueue)
#pragma clang diagnostic pop
#else
    if (dispatch_get_specific([GPUImageContext contextKey]))
#endif
    {
        block();
    }else
    {
        dispatch_async(videoProcessingQueue, block);
    }
}

3.多用派發(fā)少用同步鎖

對于atomic特質(zhì)來修飾的屬性,我們通常這樣來實現(xiàn)

- (NSString *)name
{
    @synchronized (self) {
        return _name;
    }
}

- (void)setName:(NSString *)name
{
    @synchronized (self) {
        _name = name;
    }
}

改進方法,使用串行隊列,將讀取操作以及寫入操作都安排在同一個隊列里,即可保證數(shù)據(jù)的同步。正如GPUImage (https://github.com/BradLarson/GPUImage) 中將所有的渲染隊列都放在VideoProcessingQueue串行隊列中處理。

- (NSString *)name
{
    __block NSString *name;
    void (^block)() = ^{
        name = @"iOS";
    };
    
    if (dispatch_get_specific(key)) {
        block();
    }else {
        dispatch_sync(_syncQueue, block);
    }
    
    return name;
}

- (void)setName:(NSString *)name
{
    void (^block)() = ^{
        _name = name;
    };
    
    if (dispatch_get_specific(key)) {
        block();
    }else {
        dispatch_async(_syncQueue, block);
    }
}

參考

https://github.com/BradLarson/GPUImage](https://github.com/BradLarson/GPUImage

Effective Objective-C 2.0

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容