Saturday, June 29, 2019

iphone - Why is `&` (ampersand) put in front of some method parameters?



I'ver wondered, why is it that in front of an NSError, such as below, do we put: &error and not error?



E.g.




NSArray *result = [managedObjectContext executeFetchRequest:fetchRequest error:&error];


Hope you can explain, also is this always the way or only in certain situations this is needed? Thanks.


Answer



You need to take the address of error because the function needs to modify it. error is passed by pointer, so you need the "take address" operator & for it.



C and Objective-C pass parameters by value. If you pass error without an ampersand and the method that you call modifies it, your function that made the call would not see any changes, because the method would operate on its local copy of NSError*.




You know that you need an ampersand in front of the corresponding parameter if you look at the signature of the method and see ** there:



- (NSArray *)executeFetchRequest:(NSFetchRequest *)request error:(NSError **)error
// ^ one ^^ two

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...