3

我刚刚将我的代码从 Objective-C 切换到 Objective-C++。除了两条线,一切都很顺利。

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

这条线抱怨说

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

与第一个相关的第二个错误来自以下行:

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

它抱怨说

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

在 ObjC 和 ObjC++ 之间的差异中我错过了什么吗?

4

3 回答 3

7

你要:

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

不是:

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

(注意-UTF8String的返回值。)

于 2010-03-08T20:44:48.730 回答
2

但是你知道你也可以像这样告诉 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]];
于 2010-03-08T20:55:55.503 回答
1

您不能将 char *(UTF8String 返回的)分配给 NSString *。这适用于一般情况;但是,C++ 编译器显然对此更加严格。看来您的代码只是靠运气编译的;您想将 UTF8String 位向下移动一个语句;CGContextShowTextAtPoint(context, 2, 8, text1, strlen([text1 UTF8String]));

于 2010-03-08T20:45:55.530 回答