Write NSData to a file?
29,628
Try using :
NSError *error = nil;
path=@"/Users/aryaxt/Desktop/test2.avi";
[data writeToFile:path options:NSDataWritingAtomic error:&error];
NSLog(@"Write returned error: %@", [error localizedDescription]);
That'll tell you why the write is failing.
Author by
aryaxt
Updated on August 29, 2020Comments
-
aryaxt over 3 years
I am trying to write an nsdata to a file on my disk, I have the following code and it doesn't work, am i doing anything wrong?
Boolean result = [data writeToFile:@"/Users/aryaxt/Desktop/test2.avi" atomically:YES];
test2.avi doesn't exist, I am assuming that writeToFile would create it for me
-
Jonathan Grynspan over 13 years
error
should only be examined if the method returnsNO
. Foundation classes may put other objects or fake errors or even garbage in the error argument. (That's not to say that they do, but it's part of the programmer contract that they can, so be careful.) -
Coldsteel48 almost 9 yearsI have a side question a bit off topic from the documents:Discussion This method may not be appropriate when writing to publicly accessible files. To securely write data to a public location, use NSFileHandle instead. For more information, seeSecuring File Operations in Secure Coding Guide." So should I still use it or not ?
-
Coldsteel48 almost 9 years"publicly accessible files" What does it mean ?
-
John Franklin about 6 yearsMany people have upvoted Jonathan's comment about only checking the
error
if the method returnsNO
. I agree, this is true for released production code, and doubly so when sending the error to the user. The check was left out here partly for brevity and partly because theNSLog()
call in this case is used for debugging during development. -
Elise van Looij over 5 yearsThis code is quite old and doesn't take sandboxing into account. Also, check the warnings in Apple's Secure Coding Guide Race Conditions and Secure File Operations