Reputation: 15
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;
}
Upvotes: 1
Views: 1902
Reputation: 35925
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]);
Upvotes: 5
Reputation: 12003
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.
Upvotes: 2
Reputation: 14178
I don't know that printf can handle an NSString. Try somethign like:
printf ("%s\n", [getXMLElementFromString()cString]);
Upvotes: 1