开发者

How does an Objective-C method have access to the callee's ivars?

I was reading Apple's documentation, The Ob开发者_如何学Gojective-C Programming Language (PDF link). On pg. 18, under The Receiver’s Instance Variables, I saw this.

A method has automatic access to the receiving object’s instance variables. You don’t need to pass them to the method as parameters. For example, the primaryColor method illustrated above takes no parameters, yet it can find the primary color for otherRect and return it. Every method assumes the receiver and its instance variables, without having to declare them as parameters.

This convention simplifies Objective-C source code. It also supports the way object-oriented programmers think about objects and messages. Messages are sent to receivers much as letters are delivered to your home. Message parameters bring information from the outside to the receiver; they don’t need to bring the receiver to itself.

I am trying to better understand what they are describing; is this like Python's self parameter, or style?


Objective-C is a strict superset of C.

So Objective-C methods are "just" function pointers, and instances are "just" C structs.

A method has two hidden parameters. The first one is self(the current instance), the second _cmd (the method's selector).

But what the documentation is describing in page 18 is the access to the class instance variables from a method.

It just says a method of a class can access the instance variables of that class. It's pretty basic from an object-oriented perspective, but not from a C perspective.

It also say that you can't access instance variables from another class instance, unless they are public.


While I would not say that it is a "slam" against Python, it is most certainly referring to the Python style of Object Orientation (which, in honesty, is derived from the "pseudo-object orientation" available in C (whether it is truly OO or not is a debate for another forum)).

It is good to remember that Python has a very different concept of scope from the rest of the world — each method more or less exists in its own little reality. This is contrasted with more "self-aware" languages which either have a "this" variable or an implicit instance construct of some form.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜