当块试图将其自身设置为nil时,如何避免保留周期警告?

时间:2015-01-15 08:53:19

标签: ios objective-c

我正在阅读SimpleAudioPlayer的源代码,并发现当playBlock尝试设置自己的nil时,Xcode会发出警告。

我不知道如何摆脱这个警告,或者我们必须将playBlock设为零吗?

- (void) playFiles:(NSArray*) filesList withCompletionBlock:(CompletionBlock) completion
{
    __block int idx = 0;
    __block void(^playBlock)();
    playBlock = ^() {
        if (idx >= filesList.count) {
            if (completion) {
                completion ( YES );
            }
            playBlock = nil; //Capturing 'playBlock' strongly in this block is likely to lead to a retain cycle
            return ;
        }
        [self playFile:filesList[idx] withCompletionBlock:^(BOOL completed) {
            playBlock ();
        }];
        idx ++;
    };

    playBlock ();
}

1 个答案:

答案 0 :(得分:2)

无需设置playBlock = nil;也不会使用__block修饰符声明它。编译时修改后的代码(见下文)没有警告或错误。

- (void) playFiles:(NSArray*) filesList withCompletionBlock:(CompletionBlock) completion
{
    __block int idx = 0;
    void(^playBlock)();
    playBlock = ^() {
        if (idx >= filesList.count) {
            if (completion) {
                completion ( YES );
            }
            return ;
        }
        [self playFile:filesList[idx] withCompletionBlock:^(BOOL completed) {
            playBlock ();
        }];
        idx ++;
    };

    playBlock ();
}