NSLog, NSError, плохой доступ

Я делал довольно обычный addPersistentStore к NSPersistentStoreCoordinator, и это сгенерировало &error код.

Таким образом, я перешел в NSLog это, и получило ошибку доступа, когда я сделал это:

    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

который, кажется, общая идиома.

Когда я переформатировал ошибочный оператор следующим образом:

     NSLog(@"Unresolved error   %@",   [error userInfo]);

... проблема ушла.

Даже NSZombie не захватывал плохую ошибку доступа правильно!

Какие-либо идеи?

6
задан Bartłomiej Semańczyk 26 October 2015 в 09:21
поделиться

2 ответа

How are you catching the error?

The correct way, as described by bbum, is:

NSError *error;
BOOL success = [blah blah:blah error:&error];
if (!success) {
    NSLog(@"Error: %@ %@", error, [error userInfo]); //Or other error handling (e.g., [NSApp presentError:error]).
} else {
    //Succeeded—ignore the error variable entirely
}

(That's for a method blah:error:that returns a BOOL; the example in the question bbum answered was for a method that returned an object. The error-handling pattern is the same for both cases.)

According to his Twitter updates shortly afterward, some APIs will output an error object under the hood even if what you asked for succeeded, which means that testing the error variable instead of the BOOL return can fool you. I think this is what happened to you.

The solution is to only look at the error object if the API reports failure.

18
ответ дан 8 December 2019 в 12:20
поделиться

Не забудьте запустить NSError со значением nil

NSError* err = nil;
[anObject doSomethingGetError:&err];
if (err) {
    NSLog(...);
}

Если это не поможет, это ошибка API

1
ответ дан 8 December 2019 в 12:20
поделиться