读书人

IOS4 note 四

发布时间: 2012-06-28 15:20:03 作者: rapoo

IOS4 note 4

Data Type Qualifiers

?

?

A variable’s data? type can be declared with a qualifierbefore? the name of? the?type,

modifying something about how that variableis to be used. For example, the declara-

tion can be preceded by the term const,which means that? it? is?illegal to change? the? variable’s?value;? the? variable must be? initialized?in? the? same?line? as? the

declaration, and that’s the only value itcan ever have.

You can use a const variable as analternative way (instead of #define) to prevent “magic

numbers” and similar expressions. Forexample:

const NSString* MYKEY = @"Howdy";

?

?

Another commonly used qualifier? is static. This? term?is unfortunately used? in? two

rather different ways? in C;?the way? I commonly use? it? is? inside a?function.? Inside a

function, static indicates that the memoryset aside for a variable should not be re-

leased after the function returns; rather,the variable remains and maintains its value

for the next time the function is called. Astatic variable is useful, for example, when

you want to call a function many timeswithout the overhead of calculating the result

each time (after the first time). Firsttest to see whether the static value has already been

calculated: if it hasn’t, this must be thefirst time the function is being called, so you

calculate it; if it has, you just returnit. Here’s a schematic version:

int myfunction() {

???static int result = 0; // 0 means we haven't done the calculation yet

???if (result == 0) {

???????// calculate result and set it

??? }

???return result;

}

A very?common use of? a? static variable? in Objective-C? is?to? implement? a? singleton

instance returned by a class factorymethod. If that sounds complicated, don’t worry;

it isn’t. Here’s an example from my owncode, which you can grasp even though we

haven’t discussed Objective-C yet:

+ (CardPainter*) sharedPainter {

???static CardPainter* sp = nil;

???if (nil == sp)

???????sp = [[CardPainter alloc] init];

???return sp;

}

?

That code says: If the CardPainter instance sp has never been created, create it, and in any?case, now return it.

?

读书人网 >操作系统

热点推荐