Accessing NSError if no error exists


#1

I think I’m reading something wrong.

The book states, “Don’t try to access the NSError unless the return value indicates that an error has occurred; if the NSError object doesn’t actually exist, trying to access it will crash your program.”

I had actually tried to do this (or so I thought) but nothing crashed. I merely was given (null) as the 'localizedDescription" in my output.

Maybe I don’t understand what ‘accessing the object’ means.

Here’s my code:

    // Test the returned BOOL, and query the NSError if the write failed
    if (success) {
        NSLog(@"done writing /tmp/coo.txt succeeded: %@", [error localizedDescription]);
    } else {
        NSLog(@"writing /tmp/cool.txt failed: %@",[error localizedDescription]);

#2

If the method fails, Apple creates the NSError object and puts its address in the variable error.

But, Apple makes no promises about what they put there if the method is successful.

So, what you did worked fine here, but Apple doesn’t promise that is going to be OK. In fact, I suspect Apple isn’t touching that pointer, so if there were garbage there before, there will be garbage after. Try this:

[code]NSError *error = (NSError *)5;

… Call the method supplying &error …

if (success) {
NSLog(@“done writing /tmp/coo.txt succeeded: %@”, [error localizedDescription]);
} else {
NSLog(@“writing /tmp/cool.txt failed: %@”,[error localizedDescription]);
[/code]


#3

That gives me a compile error, “Cast of ‘int’ to ‘NSError *’ is disallowed with ARC”

Is that what was expected? If so, uhhh…can you explain?


#4

Oh, the compiler has become so strict! No, I was just trying to put a random garbage address into the pointer. My mistake.

Try changing the assignment to this:

NSError *error = nil; error += 5;