[英]Cannot find file when converting NSString to char*
因此,我有一个独立于平台的API,用于加载文件,它以char *作为值。 我在GetResource函数中编写了一些使用字符串文字的测试代码,它工作正常。 但是,当我转换为使用char *并转换回NSString时,找不到该文件。
工作代码:
bool GetResource(const char* filePath, uint8*& allocatedBuffer, uint32& size) {
bool success = false;
NSString* path = [[NSBundle mainBundle] pathForResource: "models/testModel" ofType: @"obj"];
不起作用的代码:
NSString* nsModelString = @"models/testModel";
gDatastore->GetResource([nsModelString UTF8String], buffer, size);
....
bool GetResource(const char* filePath, uint8*& allocatedBuffer, uint32& size) {
bool success = false;
NSString* nsFilePath = [NSString stringWithFormat:@"%c" , filePath];
NSString* path = [[NSBundle mainBundle] pathForResource: nsFilePath ofType: @"obj"];
谁能告诉我我用错了什么? 有没有一种简单的方法可以查看NSString并查看其内容?
要查看NSString来查看内容,可以在调试器中查看它,也可以使用:
NSLog(@"nsFilePath: %@", nsFilePath);
我认为问题的至少一部分在这条线上:
NSString* nsFilePath = [NSString stringWithFormat:@"%c" , filePath];
%c
是单个8位无符号字符的格式说明符。 对于C风格的字符串,您可能要使用%s
,这是8位无符号字符的以null终止的数组的格式说明符。
同样,从C字符串转换为NSString的更直接方法是使用NSString类的+ (id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc
方法。 有关更多详细信息,请参见NSString类参考 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.