tags:

views:

39

answers:

2

Hi,

I am working through a book on Cocoa and Objective-C. In the example for nested method calls:

[NSString stringWithFormat:[prefs format]];

I am assuming that prefs is the return type for the nested method call to format...is this correct ?

Thanks,

Scott

+4  A: 

Nope, in that case prefs will be an instance of an object. The return type will be an NSString *, since that's what stringWithFormat: takes. If it's part of a wider example then look for a declaration of the 'prefs' object. If it's just a throwaway line then you'll have to trust me for now. Rest assured: [object message] always sends that message to that object. The return type is defined by the message declaration and is assumed to be 'id' if the declaration can't be found.

It's not a particularly safe bit of code, by the way. If the result of [prefs format] contains any formatting characters then NSString will attempt to access things on the call stack that aren't there.

Tommy
The fact that the method is called -format potentially means that a formatting string might be what it returns. It would seem a bit pointless though if it has no actual format specifiers in it.
JeremyP
What a difference a day makes! Looking at this now and reading your answer, I've got it. Thanks!
Scott Davies
+3  A: 

No, the return type is only shown in the function declaration. Prefs is the name of the object whose method is being called (or the receiver, in Obj-C speak). In a Java-type syntax, the line would look like

NSString.stringWithFormat(prefs.format());
Sam Dufel
Ah, thank you for the Java code! Coming from a C#/Java background, so Obj-C is a little strange.
Scott Davies