为什么要检查nil的静态变量,如果它在上一行被初始化为nil? [英] Why should you check a static variable for nil if it was initialized to nil on the previous line?

查看:157
本文介绍了为什么要检查nil的静态变量,如果它在上一行被初始化为nil?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是来自苹果的iOS核心数据教程,我认为条件语句检查对象是否是nil是奇怪的。如果条件前的行将对象设置为nil,那么对象总是不会评估为nil?

Below is a code sample from Apple's iOS Core Data tutorial and I thought it was weird that the conditional statements are checking if the object is nil. Wouldn't the object always evaluate to nil if the line before the conditional sets the object to nil?

// A date formatter for the time stamp
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil) {
    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
}


推荐答案

$ c> static 。每当执行通过该语句时,该变量不会被设置为 nil 。它只能在程序启动时设置。

Because of the static. This variable is not set to nil whenever the execution passes through that statement, it 's only set on program startup.

这是静态存储持续时间变量的一个特性。它们在启动时设置为其初始化值,并保留在此之后设置它们的任何值。例如,以下代码:

That's a feature of static storage duration variables. They're set to their initialised value at startup and retain whatever value you set them to after that. For example, the following code:

void plugh(void) {
    static int xyzzy = 0;
    printf (" %d", xyzzy); // or Obj-C equivalent.
    xyzzy++;
}

不会输出一个长的零字符串,如果你称之为hundered次。它将输出:

will not output a long string of zeros if you call it a hundered times. It will output:

0 1 2 3 4 ...

在Apple代码的情况下,这意味着日期格式化程序将根据需要创建(除非您将回设置 nil 只有一次。如果对象创建是一件不平凡的事情,这对于性能来说可能是重要的,但即使不是,连续地重新创建你可以简单地重复使用的东西没有意义。

In th case of the Apple code, it means the date formatter will be created on demand and (unless you set it back to nil somewhere else) only once. This can someties be important for performance if the object creation is a non trivial thing but, even if not, there's no point in continuously recreating something you can simply re-use.

这篇关于为什么要检查nil的静态变量,如果它在上一行被初始化为nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆