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

I was reading Apple's documentation, The Objective-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.

Related

Do Objective-C objects get their own copies of instance methods?

I'm new to Objective-C and was wondering if anyone could provide any information to clarify this for me. My (possibly wrong) understanding of object instantiation in other languages is that the object will get it's own copies of instance variables as well as instance methods, but I'm noticing that all the literature I've read thus far about Objective-C seems to indicate that the object only gets copies of instance variables, and that even when calling an instance method, program control reverts back to the original method defined inside the class itself. For example, this page from Apple's developer site shows program flow diagrams that suggest this:
https://developer.apple.com/library/mac/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html#//apple_ref/doc/uid/TP40011210-CH4-SW1
Also in Kochan's "Programming in Objective-C", 6th ed., pg. 41, referring to an example fraction class and object, the author states that:
"The first message sends the setNumerator: message to myFraction...control is then sent to the setNumerator: method you defined for your Fraction class...Objective-C...knows that it's the method from this class to use because it knows that myFraction is an object from the Fraction class"
On pg. 42, he continues:
"When you allocate a new object...enough space is reserved in memory to store the object's data, which includes space for its instance variables, plus a little more..."
All of this would seem to indicate to me that there is only ever one copy of any method, the original method defined within the class, and when calling an instance method, Objective-C simply passes control to that original copy and temporarily "wires it" to the called object's instance variables. I know I may not be using the right terminology, but is this correct? It seems logical as creating multiple copies of the same methods would be a waste of memory, but this is causing me to rethink my entire understanding of object instantiation. Any input would be greatly appreciated! Thank you.
Your reasoning is correct. The instance methods are shared by all instances of a class. The reason is, as you suspect, that doing it the other way would be a massive waste of memory.
The temporary wiring you speak of is that each method has an additional hidden parameter passed to it: a pointer to the calling object. Since that gives the method access to the calling object, then it can easily access all of the necessary instance variables and all is well. Note that any static variable exists in only a single instance as well and if you are not aware of that, unexpected things can happen. However, regular local variables are not shared and are recreated for each call of a method.
Apple's documention on the topic is very good so have a look for more info.
Just think of a method as a set of instructions. There is no reason to have a copy of the same method for each object. I think you may be mistaken about other languages as well. Methods are associated with the class, not individual objects.
Yes, your thinking is more or less right (although it's simpler than that: behind the scenes in most such languages methods don't need to be "wired" to anything, they just take an extra parameter for self and insert struct lookups before references to instance variables).
What might be confusing you is that not all languages work this way, in their implementations and semantically. Object-oriented languages are (very roughly) divided into two camps: class-based, like Objective-C; and prototype-based, like Javascript. In the second camp of languages, a method or procedure really is an object in its own right and can often be assigned directly to an object's instance variables as well - there are no classes to lookup methods from, only objects and other objects, all with the same first-class status (this is an oversimplification, good languages still allow for sharing and efficiency).

Is the `id` type used often writing Objective C programs?

I'm reading the book "Programming in Objective C" and he explained not too much on the id type and didn't give much exercise on it, so I'm wondering how often do you use id and if programmers most of the time avoid it? (since he explained some issues with it)
I'm sure it's used, would be great if you can mention some cases it is the only solution..like real life programming cases from some kind of app development.
id is the universal type in Objective C. It can represent a * of any Objective-C type, such as NSString *, NSArray *, etc. The neat thing about Objective-C is that you can send messages to id, and if the object on the other end understands the message, it will get processed as usual without the sender having to know the real type.
It's commonly used when defining anything generic. For example, NSArray is an array of ids; it's up to the programmer to put a specific kind of object in the container (e.g. NSNumber, NSString, etc.). It's used in a lot of other places in Objective-C (such as when defining IBActions for the interface builder, when defining init methods, etc.).
id is the generic object type in Objective-C. It can hold any object.
one real world example: parsing json you wont know, if the root element is a array or a dictionary. But id would take them both.
I use it a lot, but often in conjunction with a protocol definition: id<NetworkPrinterProtocol>. This means that it should be an object of any kind but it does fulfill the NetworkPrinterProtocol. Often used for defining delegates.
see WP: Objective-C — Dynamic Typing
The id is kind of like a catch-all data type. It is used to hold values of any type.
Common uses are for the return type of init... methods. It's used by the collection classes since they can hold any object. See the various getter methods return values and the various methods for adding/setting objects in the mutable version of collection classes.
It's also used in combination with protocols when you need a reference to an object that can be any class but must adhere to a protocol. Examples include many of the delegate properties such as the UITableView delegate.

Function call instead of self messaging — When to use what?

In Objective-C, when I want to call a subroutine, I send a message to an object, like:
[self mySubroutine:myParameter];
There is a (negligible?) performance penalty, so I could just use a C-style function call:
mySubroutine(myParameter);
The implementation of the latter would then reside outside the class’s #implementation context.
Is this a no-no? Is it common? Is there a best-practice on this?
Note that those are not necessarily equivalent. Since -mySubroutine is an instance method, it probably needs to access a given instance. In that case, your mySubroutine() function should have another parameter for the instance, too.
In general, use a method. If you’re worried about performance,1 you can always get an IMP to the method and use it as a function instead of the standard Objective-C message dispatch infrastructure.
That said, some disadvantages of using functions:
They cannot be overridden by subclasses;
There’s no introspection (when using the runtime to obtain a list of methods declared by an Objective-C class, functions aren’t enumerated);
They cannot be used as accessors/mutators of declared properties;
They aren’t visible to Key-Value Coding;
They cannot be directly used for Objective-C message forwarding;
They cannot be directly used in the various cases where a Cocoa API expects a selector (e.g. when using NSTimer).
Some advantages of using functions:
They cannot be overridden by subclasses (if you want to prevent this);
There’s no introspection (if you want to prevent this);
They can be inlined;
They can have file scope (static), preventing code from other files from accessing them.
1When you’ve determined that the message dispatch infrastructure is actually a bottleneck. This does happen; for instance, some Apple audio examples do not use Objective-C for audio processing.
Edit: Based on OP’s comment, another advantage of functions is that they aren’t necessarily related to a class. If the computation of an approximate value for the sine of an angle doesn’t depend on an Objective-C instance, there’s no need to make it a method — a function is a better fit.
It might be worth using where you have static utility functions, such as in a maths library.
In general though, if you need methods that act on the state of an object, the C approach won't be much use, as you won't have implicit access to self, unless you explicitly pass it as a parameter.
You may also run into namespace issues. With the Objective-C different classes can share method names, with the c approach all your functions will need different signatures.
Personally I would always use objective-c methods, the performance difference will be negligible.

What is the definition of Convenience Method in regards to Objective C?

In most languages I have dealt with, one something is called a convenience method, it means that the method does some small task that gets done very frequently, and therefore it is more convenient to use said method.
In Objective-C does this definition hold true? Or is it generally only used to describe class methods that return a prebuilt object? ex. [NSString stringWithContentsOfFile:...]
Is this just a preference thing, or are there some hard and fast definition for these terms?
Cheers,
Stefan
What you are talking about is actually more specifically a "convenience constructor" in Objective C. (Note that it's not really a constructor in the C++/Java/C# sense, it's actually an object initializer/factory method, but it seems to be the convention to call the "convenience constructors"). "Convenience constructors" in Obj C are a convention or pattern for creating a constructor/initializer/factory method for a class which takes specific parameters. This pattern also has some special conventions that you should follow (such as autoreleasing the new object within the constructor), so that your custom classes fit in well with the built-in types.
See this page (a little way down) for more info: http://macdevcenter.com/pub/a/mac/2001/07/27/cocoa.html?page=3
As for "convenience method," this specific term doesn't have any special meaning in Objective C. You can create any type of convenience method in Obj C, and there is no expectation about what it should or should not do. It's only "convenience constructor" that has a special meaning.
So far as I know, "convenience method" means basically what you defined it to mean here: a single method or function which replaces a more complicated series of invocations because of its frequency of use.
In Objective-C, the "ordinary" way to create a new instance is something along the lines of NSSomething * mySomething = [[[NSSomething alloc] initWithParam:... andParam:...] autorelease]. Many classes provide convenience constructors which simplify these three steps (in fact, in most cases, they probably literally do exactly the same thing, but wrapped behind a class method call).

Is objc_msgSend() the significant piece that makes Objective-C object oriented?

While reading the documentation, I wonder if objc_msgSend() is actually the "core technology" in delivering the functionality for making Objective-C "object oriented". Maybe someone can explain in more detail which other pieces come into place to enable the object oriented paradigm of Objective-C?
Not entirely.
Objective-C is object oriented solely because it encapsulates data and functionality into a single container; a class.
That is pretty much all there is to "object oriented programming".
Now, there are many different kinds of object oriented programming and one critical aspect is whether or not a language uses dynamic or static dispatch.
In a statically dispatched language -- C++ is the best example (yes, I know it has virtual methods that give a form of dynamic dispatch) -- a method call is wired up at compile time and cannot change at runtime. That is, the implementation of the method that will be used to fulfill the method call is fixed during compilation and cannot change at runtime.
With a dynamically dispatched language like Objective-C, the implementation of the method that will be used to fulfill a method call is determined each time the method call happens. Thus, through the use of categories or the runtime's API, it is possible to change a method's implementation while an application is running (this is actually how Key Value Observation works, for example).
objc_msgSend() is the hook that does the dynamic dispatch. It takes a reference to an object or a class & a method name -- a selector or SEL, as it is called -- and looks up the implementation on the object or class that goes by that method name. Once the implementation is found, it is called.
If no implementation is found, objc_msgSend() will then take a series of steps to see if the class or instance wants to handle the unrecognized method call somehow, allowing one object to stand in for another (proxying) or similar functionality.
There is a lot more to it than that. I would suggest you read Apple's documentation for more information.
There's quite a bit more to it.