Using Cocoa to resolve Unix file paths with tildes

Quick! How do you expand a file path that has a tilde in a program? Luckily, you can use NSString to resolve the path for you. So, if you path looks like “~/Library”, you can use the stringByExpandingTildeInPath method to resolve the tilde to the full path: “/Users/johndoe/Library/”. Here is s snippet of code to show that:

NSString *myString = [[NSString alloc] initWithString:[@”~/Library” stringByExpandingTildeInPath]];

Of course don’t forget that you need to allocate memory for the string and initialize it! Now, if you need to use this function within a C++ App, don’t fret. You can add the above listed code to a C++ file and so long as you set the file to compile as a sourcecode.cpp.objc file,in the File Type drop down list in the “Info” dialog box, you should be good to go.

Click here for the Objective-C project

Leave a Reply