Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

objective c - Why passing &error instead of error in Cocoa programming?

In Cocoa programming, when dealing with NSError, why we are passing &error to a message instead of error?

NSError *error;
if (![managedObject.managedObjectContext save:&error])
   //Code
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The save method takes a pointer to a pointer. There's a good explanation on Cocoa Tutorial: Using NSError to Great Effect

Passing Pointers to Pointers

Using the NSError class in the above example is quite simple. I just pass it in and if the call failed for whatever reason I have an NSError object to explain what the problem was. But how does the other side of that call work?

The first part of this is to understand the concept of passing a pointer to a pointer rather than a pointer to an object. Normally when a message is sent, a pointer to the object is being passed in the message. This is denoted with the single asterisk(*) in the method signature such as

-(void)appendString:(NSString*)newString This is different then passing a pointer to a pointer. First, that type of argument is denoted with two asterisk(**) such as:

-(BOOL)save:(NSError**)error Second, the other difference is this allows the receiving method to control what the pointer (that the pointer is pointing to) is referencing. This is arguably one of the more confusing parts of pointer programming but once you get it, it is a very powerful tool. To put it another way, by passing a pointer to the pointer, the receiving method can decide what your variable’s value is. As you can see in my code above, I initialized the error variable to nil. However, if the save call fails, that variable will no longer be nil but will reference an actual NSError object which I can than interrogate.

If you wish to understand how this works, I would suggest the double indirection wikipedia article as a great starting point.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...