简体   繁体   English

Objective-C ++中的字符串

[英]Strings in Objective-C++

I just switched my code from Objective-C to Objective-C++. 我刚刚将我的代码从Objective-C切换到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++? ObjC和ObjC ++之间的区别是否有一些错过的东西?

You want: 你要:

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

Not: 不:

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

(Notice the return value of -UTF8String .) (注意-UTF8String的返回值。)

But did you know that you can also just tell the NSString to draw itself, like so? 但是你知道你也可以告诉NSString自己画画吗?

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

You can't assign a char * (which UTF8String returns) to an NSString *. 您不能将char *(UTF8String返回)分配给NSString *。 This holds true for the general case; 这适用于一般情况; however, the C++ compiler is obviously stricter about it. 但是,C ++编译器显然对它更加严格。 It seems your code compiled by a mere stroke of luck; 看来你的代码只是运气而已; you want to move the UTF8String bit one statement down; 你想把UTF8String的一位语句向下移动; CGContextShowTextAtPoint(context, 2, 8, text1, strlen([text1 UTF8String]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM