在iOS中修改方法里面的BOOL

时间:2012-10-31 05:23:12

标签: objective-c ios parameter-passing pass-by-reference

我有UITableView显示包含图片的单元格。在cellForRowAtIndexPath方法上,我启动连接以获取图像。我想跟踪已经请求的图像,以避免多次请求相同的图像。

我设置了这样的方法

+(void) setImageFromURL:(NSURL*) url fromImage:(UIImage*) srcImage to:(UIImageView*) dstImage wasRequested:(BOOL*) requested;

并像这样称呼它

[Utils setImageFromURL:event.thumbURL fromImage:event.thumbImage to:cell.image wasRequested:event.thumbRequested];

其中event.thumbRequested是BOOL属性。方法看起来像这样

+(void) setImageFromURL:(NSURL*) url fromImage:(UIImage*) srcImage to:(UIImageView*) dstImage wasRequested:(BOOL*) requested{
    if (srcImage != nil) {
        dstImage.image = srcImage;
    } else if (!requested) {
        requested = YES;
        @try {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSData * data = [[NSData alloc] initWithContentsOfURL: url];
                if ( data == nil )
                    return;
                dispatch_async(dispatch_get_main_queue(), ^{
                    __block UIImage* srcImage = [UIImage imageWithData: data];
                    dstImage.image = srcImage;
                });
                [data release];
            });
        }
        @catch (NSException *exception) {
            NSLog(exception.debugDescription);
        }
    }
}

我的问题是BOOL由于Objective-C中的值传递行为而未发生变化。任何人都可以推荐一种方法,以便能够从mehod内部更新事件对象中的BOOL吗?

1 个答案:

答案 0 :(得分:6)

该行:

requested = YES;

需要:

if (requested) {
    *requested = YES;
}

检查只是nil传入了requested

编辑:调用应该是:

BOOL requested = event.thumbRequested;
[Utils setImageFromURL:event.thumbURL fromImage:event.thumbImage to:cell.image wasRequested:&requested];
event.thumbRequested = requested;