Search code examples
cocoaencryptionnsdatawritetofile

Write data to file Cocoa?


I need to use the writeToFile: methods in writing data (that is encrypted) to a file. However, say I have:

NSData *encryptedData = [data AES256EncryptWithKey:key];

And I write the encryptedData to a file by:

[encryptedData writeToFile:@"file.txt" automatically:YES];

This for some reason does not write the data to "file.txt." This is a very simple question and I know I am missing something super basic. If file.txt is not actually there, it must be created.


Solution

  • This probably has nothing to do with Cocoa or NSData.

    On Unix (like Mac OS X), paths that start with / are absolute. Paths that start with ~ are relative to the current user's home directory. Anything else (such as file.txt) is relative to the current directory. When running something from Xcode, that is the path of the executable (the compiler's output path).

    So, to write that to the desktop, that would be:

    [encryptedData writeToFile:@"~/Desktop/file.txt" atomically:YES];
    

    For the documents folder, that would be:

    [encryptedData writeToFile:@"~/Documents/file.txt" atomically:YES];
    

    Don't forget that paths are also case-sensitive.