C++ and Objective-C string manipulations

… and a bit of iOS file faffing.

Getting paths to files inside the iOS application’s bundle:

NSString* objPath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"obj"];

‘objPath’ will now contain the full path to the file (test.obj in this example). Which is great if you’re going to poke it into an Obj-C function that understands NSStrings. However if you have C++ code it’ll probably want to be a std::string.

So to convert an NSString to a C++ std::string you can do this:

std::string filepath = [objPath cStringUsingEncoding:[NSString defaultCStringEncoding]];

And now you have a std::string with the contents of the NSString. Coding in Objective-C++ is like this, lots of converting one version of a concept to another.

If you like, you can also extract the path to a file using some simple C++:

std::string path = "root/data/home/file1.txt";
// no error checking here
std::string prefix = path.substr(0, path.find_last_of('/'));

C++ and Objective-C, making your programming efforts feel like it’s still 1990. I wrote a file parser in straight C++, it was like stepping back into my software engineering degree. There will be a post about it later, it’ll involve vi and a 9600bps serial terminal.

I found the following Stack Overflow questions useful:

About James

If this were the 80s I'd be sat in front of a C64 or Speccy, or taking VCRs apart.