1

Silly as it may sound, I am trying to write a simple function 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;
}

3 Answers 3

5

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]);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for helping, marvellous.
2

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.

1 Comment

The first form should almost always be avoided -- if an attacker can every specify a format string, you can get screwed over real fast.
1

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

 printf ("%s\n", [getXMLElementFromString()cString]);

2 Comments

I still would argue using NSLog() over printf() if you're going to be doing any serious Cocoa work.
Prefer -UTF8String over -cString — check the NSString documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.