objective-c 递归使用块

objective-c using blocks with recursion

我正在编写 iphone 应用程序。当我在 Objective-C、
中使用带递归的块时 我收到

的警告消息

Capturing addImageToUploadEntity strongly in this block is likely to lead to a retain cycle.

我创建了一个名为addImageToUploadEntity的块,用于逐一调用异步函数[self.submissionEntity addImageData: toImageAlbumType: finish^{}]。当它到达底部 case (index <= 0) 时,它会重新加载 table 视图和 return.

    __block void (^addImageToUploadEntity)(NSUInteger) = ^(NSUInteger index){
        if (index <= 0)
        {
            [self.tableView reloadData];
            return;
        }

        [self.submissionEntity addImageData:[imagesPathArray objectAtIndex:index] toImageAlbumType:_currentOperatingImageAlbumType finish:^{
            // recursively call the block with index+1
            addImageToUploadEntity(index-1);
        }];
    };
    addImageToUploadEntity(5);

经过一番研究,有人建议在块内调用弱类型的函数addImageToUploadEntity()。所以我重写了这部分并尝试了。然后,我得到了 'bad access'.

的错误

我应该怎么做才能改进代码? 有了这个块,它有内存泄漏的风险吗?

    __block void (^addImageToUploadEntity)(NSUInteger);
    void (^__block __weak weakaddImageToUploadEntity)(NSUInteger);

    weakaddImageToUploadEntity = addImageToUploadEntity = ^(NSUInteger index){
        if (index <= 0)
        {
            [self.tableView reloadData];
            return;
        }

        [self.submissionEntity addImageData:[imagesPathArray objectAtIndex:index] toImageAlbumType:_currentOperatingImageAlbumType finish:^{
            // recursively call the block with index+1
            weakaddImageToUploadEntity(index+1);
        }];
    };
    addImageToUploadEntity(5);

试试这个,希望对你有帮助 -

__weak typeof(self) weakSelf = self;

__block void (^addImageToUploadEntity)(NSUInteger) = ^(NSUInteger index){
        if (index <= 0)
        {
            [self.tableView reloadData];
            return;
        }

        [self.submissionEntity addImageData:[imagesPathArray objectAtIndex:index] toImageAlbumType:_currentOperatingImageAlbumType finish:^{
            // recursively call the block with index+1
            //addImageToUploadEntity(index-1);

            [weakSelf addImageToUploadEntity:index-1];
        }];
    };
    addImageToUploadEntity(5);

addImageData:toImageAlbumType:finish: 的异步完成处理程序需要捕获对您的块的强引用。将弱引用转换回强引用,并在异步完成处理程序中使用强引用:

typedef void (^AddImageBlock)(NSUInteger);

__block __weak AddImageBlock weakAddImage = nil;

AddImageBlock addImage = ^(NSUInteger index) {
    if (index <= 0)
    {
        [self.tableView reloadData];
        return;
    }

    AddImageBlock strongAddImage = weakAddImage;
    [self.submissionEntity addImageData:[imagesPathArray objectAtIndex:index] toImageAlbumType:_currentOperatingImageAlbumType finish:^{
        // recursively call the block with index+1
        strongAddImage(index+1);
    }];
};

weakAddImage = addImage;
addImage(5);

AddImageBlock 将保持活动状态,直到最后一个异步方法处理程序被执行并释放。