Working Directory in Objective-C and Xcode: debug mode vs. executable

1.3k views Asked by At

I am writing a program in Objective-C using Xcode. My program creates a file as follows:

[@"" writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:NULL];

I would like the file to be created in the same directory as the executable. When I run the program from Xcode, the file is created in the debug directory as expected.

However, when I run the .app file, the file is created in the root directory. How can I get the program to create a file in the directory where the .app file is located.

Thanks a lot.

EDIT: This is a MacOS application

EDIT2: Well, it seems that I shouldn't be writing to the .app directory. Thanks bbum and Paul R. What is the proper way to do it? To be more concrete, here's what I am doing: each time the user clicks a button in the application, a piece of hardware connected to a serial port will send a bunch data which will be written to a new file. This can happen any number of times while the application is running, so numerous files may be created. I would like them all created in the same folder.

2

There are 2 answers

2
Paul R On BEST ANSWER

You must never make any assumptions about the initial working directory for your application, as this will depend on what method was used to launch it (e.g. Finder, Terminal (via open), Xcode, gdb, third party utility, etc). You should use an appropriate API to find a suitable directory to store temporary files or user-specific files or whatever it is you need to do. This should never be within the app's bundle and never at a path that is relative to the initial working directory.

3
bbum On

You do not want the file to be created inside the .app wrapper. That is never the right answer; your application may easily be installed somewhere where the current user does not have write access to the YourApp.app wrapper.

(For example, my main user account is non-admin and all applications are installed admin-write-only. If an app ever fails to work because it can't write to its app wrapper, the app goes in the trash.)

See this question for an outline of where files should be stored. Depends on the role of the file.