"__block"超出块时,变量将产生nil值 [英] "__block" variable results in nil value when go out of block

查看:102
本文介绍了"__block"超出块时,变量将产生nil值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用__block变量获取块中的值.但是当超出块范围时,__block变量似乎为nil.为什么会这样?

I wanna use __block variable to get value in block. But when out of block, the __block variable seems to be nil. Why this would happen?

    NSString *fileName = [Tools MD5Encode:url];
    __block NSString *filePath = nil;
    [fileList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *aFileName = obj;
        if ([aFileName isEqualToString:fileName]) {
            NSString *path = [VERSIONS_INFO_DATA_DIRECTORY stringByAppendingPathComponent:aFileName];
            filePath = path;
            NSLog(@"filePath1 %@", filePath);
            *stop = YES;
        }
    }];
    //NSLog(@"filePath2 %@", filePath);
    //filePath seems to be nil
    return filePath;

当我将代码更改为[路径复制]时,它可以工作.但是我不知道这是否是一个好主意.有决定吗?

When I change the code to [path copy], it works. But I have no idea whether this is a good idea. Any decision?

    NSString *fileName = [Tools MD5Encode:url];
    __block NSString *filePath = nil;
    [fileList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *aFileName = obj;
        if ([aFileName isEqualToString:fileName]) {
            NSString *path = [VERSIONS_INFO_DATA_DIRECTORY stringByAppendingPathComponent:aFileName];
            filePath = [path copy];
            NSLog(@"filePath1 %@", filePath);
            *stop = YES;
        }
    }];
    //NSLog(@"filePath2 %@", filePath);
    return [filePath autorelease];

推荐答案

特别是:

在没有ARC的情况下,__block的副作用还在于,在被某个块捕获时,__ block不会保留其内容.块将自动保留并释放它们捕获的所有对象指针,但是__block指针是特殊情况,并且充当弱指针.通过使用__block来避免保留周期,依靠这种行为已成为一种常见的模式.

Without ARC, __block also has the side effect of not retaining its contents when it's captured by a block. Blocks will automatically retain and release any object pointers they capture, but __block pointers are special-cased and act as a weak pointer. It's become a common pattern to rely on this behavior by using __block to avoid retain cycles.

在ARC下,__block现在像其他捕获的对象指针一样保留其内容.使用__block避免保留周期的代码将不再起作用.而是使用如上所述的__weak.

Under ARC, __block now retains its contents just like other captured object pointers. Code that uses __block to avoid retain cycles won't work anymore. Instead, use __weak as described above.

所以您需要复制.

这篇关于"__block"超出块时,变量将产生nil值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆