Command Line Tool Resources

Command line tools created in Xcode do not generate a standard OS X application bundle. If you wish to include resources with your tool, you must be manually include them and the paths must be referenced without using the normal NSBundle methods. For instance, in order to locate the path for a resource included within an “application” (which WILL have a bundle), you might make the following call to retrieve the app’s bundle and get the path for the specified resource:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"mytextfile" ofType:@"txt"];

That line of code will compile and execute without complaint using the default project template for a Command Line Tool project. However, the resulting path will be nil. Actually, the mainBundle class method will return a valid NSBundle object. However, the path returned from any of the NSBundle methods that would normally return the path to a resource will all return nil.

I wouldn’t imagine you would often want to include resources with a command line tool, but if you do, you can copy the file to the same location as the executable and reference the path by getting the executable path for the mainBundle. To include a file, add it to the “Copy Files” section of the “Build Phases” tab of the target.

Including resources

You can then obtain the path to the resource by using the mainBundle to get the path of the executable and replacing the executable file name with the name of the resource you’re looking for:

NSString *exePath = [myBundle executablePath]; NSString *resourceFolder = [exePath stringByDeletingLastPathComponent];
NSString *resourceFile = [resourceFolder stringByAppendingPathComponent:@"mytextfile.txt"];
Author image
About Brice Wilson
Software Developer and Trainer