开发者

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 reci开发者_开发技巧pe, 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.


The pointer is for the NSString that the function returns, not for the function itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜