views:

1249

answers:

2

I'm trying to understand the meaning of the value returned by [NSData writeToFile:options:error:]. The method returns a BOOL, which according to Apple's documentation is "YES if the operation succeeds, otherwise NO."

Fair enough, but if it's NO, I would have assumed that the error parameter would then be set to some retrievable NSError* value. However in results I'm coming across, that's not the case. Accordingly I'm somewhat confused, and don't know how to determine what caused the failure.

To wit, I've got this code (more or less):

NSError* error = nil;
BOOL success = [data writeToFile: filePath error: &error];
if ( error )
    NSLog( @"error = %@", [error description] );

success turns out to be NO in the code I'm running, but the NSLog statement is never executed. How come?

Howard

A: 

The writeToFile method returns TRUE on success and FALSE on failure -that's what you want to actually check for.

So, Try:

if(!success)

As your conditional instead of if( error ).

Mark Hammonds
I've tried success == NO, but in that case (and I presume in the case of trying your shorter form as well), the emitted log statement is 'error = (null)'. That's what I'm not understanding.
hkatz
+4  A: 

It's possible that data is nil, in which case [data writeToFile:error:] returns nil, but *error is not set.

Barry Wark
That's exactly what it is. Thank you. I've never been bitten before by the fact you can send a message to the nil object; At last: I now consider myself a true Objective-C programmer! :-)
hkatz