Write data to file Cocoa?
I need t开发者_运维知识库o 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.
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.
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
returns a boolean to say if it was successful or not. I'd start there, if you see a YES then the file wrote somewhere successfully.
If that doesn't work then i'd double check the object you're trying to encode supports the NSCoding protocol. If you object doesn't support NSCoding take a look at this blog post for a nifty simple way of adding it.
Also its "atomically" not "automatically" :)
精彩评论