• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

黑白Objective C的自我和C++的区别?

用户头像
it1352
帮助1

问题说明

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

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

正确答案

#1

主要区别在于 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.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfkhch
系列文章
更多 icon
同类精品
更多 icon
继续加载