复制并自动释放块中的局部变量

时间:2013-05-22 18:17:01

标签: objective-c copy block autorelease

在函数内部,我有一个局部变量,它持有作为成员变量的日期的副本。对于_date,代码顶部有无保护。

if (!_date) return;

NSDate *date = [[_date copy] autorelease];

在块中使用的函数日期中较低。

但是,在区块内有时(罕见)日期为零。在执行此操作的函数中没有其他调用发布日期。谁能解释一下发生了什么?

此处的代码示例:

    NSDate *date = [[_date copy] autorelease];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Cache Label Image
    NSDateFormatter *weekday = [[[NSDateFormatter alloc] init] autorelease];

    //Name of day label
    UILabel *nameOfDay = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
    [weekday setDateFormat: @"EEE"];
    nameOfDay.text = [weekday stringFromDate:date];
    [nameOfDay sizeToFit];

    // Draw it on background thread using ImageContext

    dispatch_async(dispatch_get_main_queue(), ^{
        if(![date isEqualToDate:_date])
            return;
        .
        .
        .
        .   
    });
});

1 个答案:

答案 0 :(得分:0)

在块执行之前,很可能_date设置为nil。当您_date阻止编译器将其作为self->_date加密时,并在复制块时保持对self的强引用,而不是_date。可能你只需要将NSDate *date = [[_date copy] autorelease];移出块。

有关详细信息,请参阅here