开发者

Difference b/w Objective C's self and C++'s this?

can someone tell the difference between obj开发者_开发知识库ective C's self and C++ this pointer?


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.

The reasons for doing so are:

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

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.

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.


Yes. One is spelt s-e-l-f. The other is spelt t-h-i-s.

Less facetiously:

self is used in Objective-C classes to represent a pointer the current instance.

this is used in C++ classes to represent a pointer the current instance.

They perform analogous roles but on entirely different structures.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜