【问题标题】:copy and autorelease local var in block在块中复制和自动释放本地变量
【发布时间】:2013-05-22 18:17:01
【问题描述】:

在一个函数中,我有一个局部变量,它保存着一个日期的副本,它是一个成员变量。代码顶部有针对 _date 的 nil 保护。

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;
        .
        .
        .
        .   
    });
});

【问题讨论】:

  • 您需要发布更多代码。上下文在这里很重要。显示整个方法,包括块。
  • 但是您不需要“nil 保护”,因为 nil 目标操作会被忽略。所以 copy 也会“返回”(实际上它不会返回任何东西,因为它永远不会被调用)nil。
  • 我确实需要这个函数的 nil 保护,因为它还在基于日期字符串的块内做一些 sizeToFit 工作。

标签: objective-c copy block autorelease


【解决方案1】:

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

更多信息请见here

【讨论】:

  • 这就是他所说的:“但是,在块内有时(罕见)日期为零。”
猜你喜欢
  • 1970-01-01
  • 2017-12-02
  • 2019-10-11
  • 2012-10-10
  • 1970-01-01
  • 2013-04-16
  • 1970-01-01
  • 2018-11-14
相关资源
最近更新 更多