开发者

Cannot find file when converting NSString to char*

So I have a platform independent API that loads a file, it takes a char* as a value. I wrote some test code in the GetResource function that used a string literal and it worked fine. However when I convert over to using the char* and converting back to an NSString the file can't be found.

Working code:

bool GetResource(const char* filePath, uint8*& allocatedBuffer, uint32& size) {

    bool success = false;
    NSString* path = [[NSBundle mainBundle] pathForResource: "models/testModel" ofType: @"obj"];

Not Working code:

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

Can开发者_StackOverflow中文版 anyone tell me what I am using wrong? Is there an easy way to look at an NSString and see the contents?


To look at the NSString to see the contents, you could either view it in the debugger or use:

NSLog(@"nsFilePath: %@", nsFilePath);

I think at least part of the problem is on this line:

NSString* nsFilePath = [NSString stringWithFormat:@"%c" , filePath];

%c is the format specifier for a single 8-bit unsigned char. For a C style string, you probably want to use %s, which is the format specifier for a null-terminated array of 8-bit unsigned characters.

Also, a more straightforward way of converting from a C string to an NSString is by using the + (id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc method of the NSString class. See the NSString class reference for more details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜