tags:

views:

257

answers:

3

Hi,

Silly as it may sound, I am trying to write a simple fuction in objective-c which returns a string and displays it, the following code nearly works but I can't get printf to accept the functions return value ...

NSString* getXMLElementFromString();

int main(int argc, char *argv[])
{
    printf(getXMLElementFromString());
    return NSApplicationMain(argc,  (const char **) argv);
}

NSString* getXMLElementFromString() {
    NSString* returnValue;
    returnValue = @"Hello!";
    return returnValue;
}

Any help out there would be much appreciated.

Richie.

+1  A: 

I don't know that printf can handle an NSString. Try somethign like:

 printf ("%s\n", [getXMLElementFromString()cString]);
Dave
Awesome, worked perfectly! Thanks mate.
Richard Smith
I still would argue using `NSLog()` over `printf()` if you're going to be doing any serious Cocoa work.
jbrennan
Prefer `-UTF8String` over `-cString` — check the NSString documentation.
Quinn Taylor
+2  A: 

You should instead use NSLog() which takes a string (or a format string) as a parameter.

You could use either

NSLog(getXMLElementFromString());

or

NSLog(@"The string: %@", getXMLElementFromString());

Where the %@ token specifies an Objective-C object (in this case an NSString). NSLog() works essentially the same as printf() when it comes to format strings, only it will also accept the object token.

jbrennan
The first form should almost always be avoided -- if an attacker can every specify a format string, you can get screwed over real fast.
Adam Rosenfield
+5  A: 

NSString* is not equivalent to a traditional C string, which is what printf would expect. To use printf in such a way you'll need to leverage an NSString API to get a null-terminated string out of it:

printf("%s", [getXMLElementFromString() UTF8String]);
fbrereto
Thanks for helping, marvellous.
Richard Smith