简体   繁体   中英

Cannot create file using Cocoa with Objective-C

I'm using Xcode to create a macOS application with Cocoa (Objective-C).

I happen to create a text file when running my app with the button Run inside Xcode, but the problem is that the file is not created when I run my application from the directory Products/Release/

Has it something to do with permissions?

NSString *sometext=@"Hello world";
NSString *path=@"test.txt";
[sometext writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];

Since you didn't use an absolute path, the path is relative to the process's current directory.

If your app is sandboxed, then the current directory is the app sandbox's Data directory. But I guess, from your symptoms, that your app is not sandboxed.

If your app is not sandboxed, and you run it from Xcode, its current directory is the directory containing the app (for example, /Users/mayoff/Library/Developer/Xcode/DerivedData/test-aegotyskrtnbeabaungzpkkbjvdz/Build/Products/Debug ). Your user id has permission to create files in this directory, so your code works when you run the app from Xcode.

If your app is not sandboxed, and you run it by double-clicking it in the Finder, its current directory is the root directory ( / ). Your user id does not (normally) have permission to create files in this directory, so your code fails when you run the app from the Finder.

You should either let the user choose where to write the file, using an NSSavePanel , or you should write the file to a directory you know you'll have write access to, like the user's Documents folder. Here's some code to write to the Documents folder:

NSURL *documentDirectoryUrl = [NSFileManager.defaultManager URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
NSURL *fileUrl = [documentDirectoryUrl URLByAppendingPathComponent:@"test.txt"];
NSString *someText = @"Hello world";
NSError *error;
if (![someText writeToURL:fileUrl atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
    // Error occurred. Details are in the error object.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM