访问块中的NSMutableDictionary属性

时间:2013-11-21 16:34:21

标签: objective-c-blocks grand-central-dispatch nsmutabledictionary

我想将UIImages保存到NSMutableDictionary中,NSMutableDictionary是块方法中的属性,

    __block UIImage *headImage = [[UIImage alloc] init];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
    headImage = [self getImageFromURL:status.user.profile_image_url];
    dispatch_async(dispatch_get_main_queue(), ^{
        [headImageView setImage:headImage];
        [[self contentView] addSubview:headImageView];
    });
});

调试getImageFromURL时,每次iconDict为空时都会找到,并且该方法在setObject:forKey之前返回。

-(UIImage *) getImageFromURL:(NSString *)imageUrl {

UIImage * image = [[UIImage alloc] init];

if(iconDict)
{
    image = [_iconDict objectForKey:imageUrl];

    if (image) {
        return image;
    }
} else {
    _iconDict = [NSMutableDictionary dictionaryWithCapacity:3];
}

image = [self loadImage:imageUrl];
[_iconDict setObject:image forKey:imageUrl];

return image;

}

这有什么担心?

1 个答案:

答案 0 :(得分:0)

我想说你需要改变代码的语义。没有理由在调用函数中存储UIImage实例,因此只需使getImageFromURL:只返回布尔成功状态即可。如果是YES,则从_iconDict获取图片:

dispatch_async(dispatch_get_global_queue(0, 0), ^{
    if ([self getImageFromURL:status.user.profile_image_url]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [headImageView setImage:_iconDict[status.user.profile_image_url]];
            [[self contentView] addSubview:headImageView];
        });
    }
});

...

- (BOOL)getImageFromURL:(NSString *)imageUrl {
    UIImage *image = [_iconDict objectForKey:imageUrl];
    if (!image) {
        image = [self loadImage:imageUrl];
        if (image) {
            if (!_iconDict)
                _iconDict = [NSMutableDictionary dictionaryWithCapacity:3];                    
            _iconDict[imageUrl] = image;
        }
    }
    return image != nil;
}