Reputation: 22939
I have been using NSError
in a few places but I don't really grasp the concept behind it. Especially why it is used using a double pointer like this:
NSError *err = nil;
NSString *s = nil;
s = [NSString stringWithContentsOfURL:url error:&err];
So why can't we just pass the variable err
to the method, which is passed as "by-reference" anyway as far as I can tell.
Thanks for some clarification
Upvotes: 3
Views: 543
Reputation: 6908
This is one of the best descriptions around about NSError.
Actually your are passing not an object but a pointer to a pointer. With this, you can set your NSError before you send a message to an object to nil and only if an error occurs, your NSError will "suddenly" hold an value so that you can do stuff like this:
NSError *err = nil;
[SomeClass doSomethingGreatWhichCanFailWithError:&err];
if(err) {
NSLog("Something failed :-(");
//TODO: Add better logging!
}
Otherwise you would have to create an instance of NSError before you send the message and than check for a property or something else if an error occured.
Upvotes: 3
Reputation: 5157
Passing an object by reference would require you to allocate and initialize an NSError object that can then be manipulated by the called method to suit the needs. This also requires to have all funcitonality either directly in NSError or require the caller to know of and use specific subclasses of NSError.
Using this method the caller does not have to create an NSError object at all. In most cases no error should occur and there is no creation of useless error objects. Additionally any class could feature a subclass of NSError to give further information. If the caller does not care about this, it interprets the returned object as simple NSError and everything is fine. If the caller is interested in details, it can cast to the subclass and get further information.
Upvotes: 2