John Smith
John Smith

Reputation: 12807

Strings in Objective-C++

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++?

Upvotes: 3

Views: 1857

Answers (3)

Williham Totland
Williham Totland

Reputation: 29019

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]));

Upvotes: 1

jlehr
jlehr

Reputation: 15597

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]];

Upvotes: 2

Michael
Michael

Reputation: 12062

You want:

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

Not:

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

(Notice the return value of -UTF8String.)

Upvotes: 7

Related Questions