There are methods in Cocoa classes that accept an address of a pointer. Most commonly the argument is address of future NSError * object in CoreData validation methods (among others). This way it is possible to put custom or owned object into the place of the address that given argument points to.
My question is: why can’t we do that with simple pointer arguments? E.g. let’s say I have a method:
- (void)addObject:(id)someObject toArray:(NSMutableArray *)array;
I can easily pass the mutable array as second argument, call addObject: on it and after the method call the array will be modified. Why is this not done with NSError * objects? Are pointers passed to methods are defined as const by default? Is this to avoid accessing NULL?
Because there’s no such thing as an
NSMutableError. Your example works because you can modify the contents of the array without modifying the pointer to the array itself. However, sinceNSErrorinstances are immutable, you cannot modify anNSError. As such, you must necessarily create a new error object. And if you want to return that error object along with some other piece of data, at least one of those must be done via an out-parameter (such as anNSError **).Nope. Inside that method you’re welcome to do this:
What’s important to remember here is that you’re only changing a pointer in a slot in memory. The memory slot corresponding to
someObjectis just a space on the stack, and you’re changing the contents of that space to have a value that points to a different allocated object than the one you were given.Any
NULLprotection you need must be done yourself.