为什么传递错误而不是错误在Cocoa编程? [英] Why passing &error instead of error in Cocoa programming?

查看:121
本文介绍了为什么传递错误而不是错误在Cocoa编程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Cocoa编程中,当处理NSError时,为什么我们将错误传递给一条消息而不是错误?

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


推荐答案

保存方法接受指针指针。 有一个很好的解释Cocoa教程:使用NSError的很大效果

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

使用NSError类上面的
例子很简单。我只是传递
它,如果调用失败的
无论什么原因我有一个NSError
对象来解释什么问题
。但是
的另一方如何工作呢?

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?

这第一部分是
理解传递
的概念b指向指针的指针,而不是指向对象的
指针。通常当发送
消息时,在消息中传递指向
对象的指针。
这在方法签名
中用单个
asterisk(*)表示,例如

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
这是不同的,然后传递一个
指针指针。首先,类型
的参数用两个
表示asterisk(**)如:

-(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: *)错误第二,另一个区别是这允许
接收方法来控制什么
指针(指针是
指向)引用
。这是
可以说是一个更混乱的
部分的指针编程,但一旦
你得到它,它是一个非常强大的
工具。换句话说,通过
传递指针到指针,
接收方法可以决定你的
变量的值是什么。正如你可以看到
上面的代码,我初始化错误
变量为nil。然而,如果保存
调用失败,该变量将不会是
更长的nil,但将引用一个
实际的NSError对象,我可以比
询问。

-(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.

如果您想了解这个
的工作原理,建议您使用 double
indirection wikipedia article
as a
great starting point。

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

这篇关于为什么传递错误而不是错误在Cocoa编程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆