Question

This is a simple one: I'm currently creating a new NSError object every time I perform a fetch on my NSFetchedResultsController. This occurs across a number of methods, so there are currently nine of them in my main view controller. Should I create one NSError as a property and use that, or is it more conventionally accepted to create a new one each time you use it?

I'm guessing the advantage of creating multiples is that if more than one error occurs, you can get at both independently, but if this is unlikely to occur, is it acceptable to use a shared one for all performFetch calls? I'm learning a lot of programming convention and technique, so apologies if this is something of a non-issue, I'd just like to get some feedback on the more typical approach to using NSError objects in a variety of places.

Was it helpful?

Solution

You aren't really creating NSError objects. You are declaring references to NSError objects and then passing the reference to a method which may point the reference at an NSError object it creates.

NSError *err; // just a reference, no object created
// this creates an object, but you don't do this
err = [NSError errorWithDomain:@"foo" code:0 userInfo:nil];

// You do this.... 
BOOL success = [fetchedResultsController performFetch:&err];

The distinction is, you aren't really creating a bunch of objects which require overhead. So if you re-use the same variable for all of them or you create a new variable for each one, it isn't going to impact performance.

So to answer the question... either use 1 variable or many as you see fit. Some code might fail on any error and refuse to continue so 1 error is fine. Other code might want to try and keep going so you keep all the errors and spew them out at the end. It's a matter of what fits best with the specific coding you are working on at the time.

OTHER TIPS

Just declaring one on the stack and passing it's address is virtually free. So you could do:

NSError *errorA;

// do something, passing &errorA
if (!errorA) {
    // do something passing &errorA again
}

Or, at hardly any additional cost (just another pointer on the stack)

NSError *errorA, *errorB;

// do something, passing &errorA
// do something, passing &errorB, that doesn't care whether the last thing succeeded

if (!errorA && !errorB) {
    // do something else
}

There's no need to worry about allocations of NSError here. It should be more about the logic of dependency between the first action success and doing a second action.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top