views:

53

answers:

2

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.

+3  A: 

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.

Carl Norum
Sorry for the poor formatting of the following code; I'll read up on how to do that ASAP.In C++, something like the following would work: NSString testString = boolString (BOOL yesNo); int * ptr = NSLog (@ *ptr );In Objective-C, it doesn't. What I don't get is that there seems to be no NSString variable named (like testString) to capture the value boolString() returns; and there also is no named pointer (like ptr) to capture the address of the unnamed NSString variable; and since the pointer is unnamed, it can't be dereferenced!
Rich
@Rich, that's right. In Objective-C, you only ever use pointers to objects, never the objects themselves. I'm sure you'll get used to it.
Carl Norum
Thanks - I'm sure I will.
Rich
A: 

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

Jeff
Sorry for the poor formatting of the following code; I'll read up on how to do that ASAP.You're saying the function works normally, making a string out of a BOOL value, so using the function as an argument for NSLog displays the returned string.I'm still wondering why a pointer is used at all.Could I, after the pattern: int foo = 7; int *pointer = printf("pointer points to the number %d\n", *pointer);have written something like this? Though this doesn't seem to work. NSString testString = boolString (BOOL yesNo); int * ptr = NSLog (@ *ptr );
Rich
To be specific, the boolString function makes a NSString, then returns a pointer to that NSString. In Objective-C, *all* objects are referred to via pointers. When you use NSLog to print a NSString, it expects a pointer to a NSString. That is why the NSString pointer returned by boolString works with NSLog.
Jeff