黑白Objective C的自我和C++的区别? [英] Difference b/w Objective C's self and C++'s this?

查看:71
本文介绍了黑白Objective C的自我和C++的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能说出目标 C 的 self 和 C++ this 指针之间的区别?

can someone tell the difference between objective C's self and C++ this pointer?

推荐答案

主要区别在于 this 是关键字,而 self 是变量.这样做的结果是,虽然 this 总是 引用正在执行特定方法的对象,但 Objective-C 方法可以自由修改 self在执行过程中.这有时被构造函数使用,它在失败时设置 self = nil.

The main difference is that this is a keyword, while self is a variable. The result of this is that while this always refers to the object that is executing a particular method, Objective-C methods are free to modify self during execution. This is sometimes used by constructors, which set self = nil on failure.

这样做的原因是:

  • 这样子类(用 self = [super init] 链接初始化器)可以看到初始化失败的时间,并且知道不要在自己的初始化器中继续.
  • 组合对象可以看到失败并知道它们没有有效的组件.
  • so that subclasses (which chain initialisers with self = [super init]) can see when the initialisation fails and know not to carry on in their own initialisers.
  • composing objects can see the failure and know that they don't have a valid component.

某些初始化程序会将 self 设置为不同但有效的对象.这可用于类集群,其中抽象"类可以在构建初始化对象时生成临时实例,但最终根据构建期间构建的属性返回不同的对象.

Some initialisers will set self to a different, but valid, object. This can be used in class clusters, where the "abstract" class can generate a temporary instance while building the initialised object, but ultimately return a different object based on the properties that were built up during construction.

另外,这意味着你可以用变量名做通常用关键字做不到的让大家迷惑的事情,比如在self中定义一个更局部的同名变量一个代码块.

In addition, it means that you can do the usual things with variable names that confuse everyone that you can't do with keywords, such as defining a more local variable with the same name self in a code block.

这篇关于黑白Objective C的自我和C++的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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