Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

caching - Using static keyword in objective-c when defining a cached variable

I'm looking at the following apple example source code:

    /*
 Cache the formatter. Normally you would use one of the date formatter styles (such as NSDateFormatterShortStyle), but here we want a specific format that excludes seconds.
 */
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil) {
    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"h:mm a"];
}

Trying to figure out:

  • Why use the static keyword?

  • How this equates to a cached variable if you set it to nil each time the method is called.

The code is from Example 4 in the Tableview Suite demo

question from:https://stackoverflow.com/questions/554969/using-static-keyword-in-objective-c-when-defining-a-cached-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Static variables retain their assigned values over repeated calls to the function. They're basically like global values that are only "visible" to that function.

The initializer statement is only executed once however.

This code initializes dateFormatter to nil the first time the function is used. On every subsequent call to the function a check is made against value of dateFormatter. If it's not set (which will only be true the first time) a a new dateFormatter is created. If it is set then the static dateFormatter variable will be used instead.

It's worth becoming familiar with static variables. They can be very convenient but have downsides too (in this example it's impossible to release the dateFormatter object for example).

Just a tip: Sometimes it can be educational to place a breakpoint in the code and have a look to see what's going on. As the complexity of your programs increase this will become an invaluable skill.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...