views:

212

answers:

3

I just switched my code from Objective-C to Objective-C++. Everything goes swimmingly except for two lines.

NSString * text1=[[NSString stringWithFormat:@"%.2f",ymax] UTF8String];

This line complains that

error: cannot convert 'const char*' to 'NSString*' in initialization

The second error related to the first is from the line:

CGContextShowTextAtPoint(context, 2, 8, text1, strlen(text1));

It complains that

error: cannot convert 'NSString*' to 'const char*' for argument '1' to 'size_t strlen(const char*)'

Is there something I missed in the differences between ObjC and ObjC++?

+5  A: 

You want:

const char * text1 = [[NSString stringWithFormat:@"%.2f", ymax] UTF8String];

Not:

NSString *text1 = [[NSString stringWithFormat:@"%.2f", ymax] UTF8String];

(Notice the return value of -UTF8String.)

meeselet
Thanks. That solved my problem, but why does NSString work in Obj-C?
John Smith
Maybe because pointer conversion is more lenient in C. NSString * is a pointer, after all, char * is a pointer too, so they cast into one another with no warnings. That's what C++ was invented for, static type checking.
Seva Alekseyev
+1  A: 

You can't assign a char * (which UTF8String returns) to an NSString *. This holds true for the general case; however, the C++ compiler is obviously stricter about it. It seems your code compiled by a mere stroke of luck; you want to move the UTF8String bit one statement down; CGContextShowTextAtPoint(context, 2, 8, text1, strlen([text1 UTF8String]));

Williham Totland
+2  A: 

But did you know that you can also just tell the NSString to draw itself, like so?

NSString *text = [NSString stringWithFormat:@"%.2f", ymax];

//  Send a message to the string to draw itself at the given point with
//  the provided font.
//
[text drawAtPoint:CGPointMake(20.0, 30.0)
         withFont:[UIFont systemFontOfSize:36.0]];
jlehr