我正在阅读SimpleAudioPlayer的源代码,发现playBlock尝试将其自身设置为nil时,Xcode将发出警告。

我不知道如何消除此警告,还是必须将playBlock设置为nil?

- (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 ();
}

最佳答案

无需设置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 ();
}

09-25 18:45