views:

593

answers:

3

Hi. How would I take a file in the application's directory (the same folder the .app is in), and get it's absolute path. Say the relative path is "Data/file.txt," how would I use Objective C to get that as an absolute path? I have the user enter their home folder name, if that is any help.

Please help,

HiGuy

+1  A: 

You should just be able to concatenate the root folder of the app, with the relative path. You can get at the app home directory with NSHomeDirectory(), so to get the absolute path you can do something like the following:

NSString *path = [NSHomeDirectory() stringByAppendingString: @"/Data/file.txt"];
Tom
Not directly related to your answer, but NSHomeDirectory() actually gave me "/Users/MyUserName/" instead of (path to app). I, instead, used NSHomeDirectory() to automatically get the home directory, without the use of an NSTextField.
HiGuy Smith
+1  A: 

Find the location of the running app by doing :

NSString * applicationPath = [[NSBundle mainBundle] bundlePath];

Which will return something like :

/Users/myUser/Library/Application Support/iPhone Simulator/User/Applications/317CF5C7-57B3-42CE-8DF4-4DD10B070D95/Assignment1a.app

Then use - (NSString *)stringByDeletingLastPathComponent to chop off the last bit.

Tyr
+4  A: 

I'd use the NSURL methods that resolve URLs for me, like so:

NSURL * bundle = [[NSBundle mainBundle] bundleURL];
NSURL * file = [NSURL URLWithString:@"../Data/file.txt" relativeToURL:bundle];
NSURL * absoluteFile = [file absoluteURL];

The "../" is necessary, because otherwise it'd try to locate the file inside your app bundle. Putting the "../" beforehand will tell it to look in the bundle's containing folder, and not in the bundle itself. Also, -[NSBundle bundleURL] is a 10.6+ API, but it's trivial to replicate the functionality using an NSURL convenience method and -[NSBundle bundlePath].

Dave DeLong