【发布时间】: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