简体   繁体   中英

Functions as pointers in Objective-C

This is a question from Learn Objective-C on the Mac...

Functions as pointers

What I typed in, as per the recipe, was:

NSString *boolString (BOOL yesNo) {
if (yesNo) { return (@"YES");
} else { return (@"NO");
} } // boolString

The pointer asterisk in the first line doesn't seem necessary, yet deleting it results in an error message. But what does it do? In

 NSString * boolString (yesNo);

what seems to be going on is a function is defined as a pointer to an NSString. The function without the asterisk

NSLog (@"are %d and %d different? %@", 5, 5, boolString(areTheyDifferent));

returns an NSString of YES or NO. But how can it return an NSString when it's a pointer? It might return the ADDRESS of an NSString; or if dereferenced it could return the CONTENTS of that address (an NSString such as YES or NO). Yet I see no place where it is dereferenced.

The function returns a pointer to an NSString object. In Objective-C you almost never deal with objects directly, only with pointers to them. As far as you're concerned, NSString * is the type you should always be using.

指针用于函数返回的NSString,而不用于函数本身。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM