What's the Point of (NSError**)error?

后端 未结 6 1113
小蘑菇
小蘑菇 2020-12-16 20:33

Example: The -save: method of NSManagedObjectContext is declared like this:

- (BOOL)save:(NSError **)error

Since

6条回答
  •  清酒与你
    2020-12-16 21:14

    @Anon is correct. I'll add: This is the Cocoa way to produce errors, in place of throwing exceptions.

    In your example, you have:

    NSError *error = nil;
    if (![managedObjectContext save:&error]) {
        // Handle the error.
    }
    

    Immediately after the call to save:, if there was an error, then the save: method will have created a new NSError object, and changed your error variable to point from nil to the new error object. That way you can examine the NSError object yourself and respond appropriately to it.

    IMO, this is cleaner than throwing an exception (which in my philosophy should only be done when something catastrophic and unrecoverable happens).

提交回复
热议问题