In the official documentation for Objective C 2.0 titled The Objective-C 2.0 Programming Language from Apple, released in 2009, there is a paragraph about Class Objects on page 28.
I don't understand what Class Objects are, and how to define them aside from the rest of the language and what properties they have. In the same document it's explained that everything in Objective-C 2.0 is an object, this object is basically a pointer to a struct that contains an isa field and the pointer itself is of type id.
From this I'm deducing that:
inheritance in Obj-C 2.0 basically consists in chaining those struct through the id and isa field
objects that are superclass construct the isa field in a way that it points to a nil object.
id is a valid datatype for pretty much everything in Objective C 2.0
when defining a class, everything that defines the class itself ( methods and variables ) is packed starting from after/below the isa pointer
Assuming that I got how Objective C 2.0 works, what is a class object and how is it different from the way instances are created? What kind of properties does a class object offer that an instance doesn't have ? Can you make a parallel with C or C++?
OK, so you define a class. We'll call him Charlie:
#interface Charlie : NSObject
#end
There's our little class! Since — like every other class in Obective-C — Charlie is an object, you can send it messages like [Charlie alloc] to have Charlie allocate an instance for you. This is what we mean by a class object: It's the object that represents the class you defined.
What is an object in Objective-C? Classes are defined based on this struct:
struct objc_object {
Class isa OBJC_ISA_AVAILABILITY;
};
And a class is represented by a struct like this:
struct objc_class {
struct objc_class *isa;
struct objc_class *super_class;
// A bunch of other members …
}
As you can see, the both start with an isa referring to a class. So a class is just an extension of normal objects.
When Charlie creates an instance, that instance's isa will point to Charlie. But what does Charlie's isa point to? Well, it points to a metaclass. A metaclass is a strange thing — it's a special kind of class that exists just to act as a class's class. You never interact with it directly; it just does its classly duties† when you interact with its sole instance, Charlie.
So that's what we mean when we talk about a class object — it's just the object that represents the class you defined in code.
† You might be wondering what a class's duties are. Well, the obvious biggie is that it's how you create your objects. But besides that, instances in Objective-C do not hold their own methods. Instead, method resolution is done based on an object's isa, so the class's most important function, besides creating instances for you, is determining what methods your object has.
what is a class object and how it's different from the way instances
are created ? What kind of properties a class object offers that an
instance doesn't have ? Can you make a parallel with C or C++ ?
Let's try to compare with C and C++. First there is no comparison to C, because C is not object oriented, so the concept of object or class does not exist. In C++ you have classes (or objects) which you declare in your .h file, there you write the definition of the class (the name, the instance variables, and methods or functions), and then in your .cpp file you implement the methods declared in the definition.
Also in C++ you can have static variables and methods, which, as you probably know, don't belong to a specific instance of the class, we could say that they affect all instances.
In objective C, a class property or a class method is analogous to the static variables and static funcions in C++.
A class object is the way objective C encapsulates the definition of a class and makes it available at runtime. You don't necessarily instantiate class objects explicitly.
Consider this class
#interface MyObject : NSObject
{
int i;
}
- (void)myFunction;
+ (void)classFunction;
#end
You can instantiate such an object using:
MyObject *obj = [[MyObject alloc] init];
Here you're using the alloc method of the MyObject class object. Something important to understand is that you don't instantiate class Objects, the compiler creates just one object, a class object, to represent the class.
Object is a structure, that has isa field pointing to its Class. This isa allows the structure to receive Objective-C messages, which makes it an Object. Class pointed by isa is used to lookup implementations for these messages.
(Interestingly, also blocks are objects and GCD structures are too. They both can receive messages, like -copy for blocks or -description for dispatch_queue.)
Class is a structure used to look-up methods of its instances. It has a list of method implementations for their instances (-methods). Classes have an isa field, so they qualify as Objects, thus can also receive messages. isa of Class points to a Metaclass, so a Class is instance of a Metaclass. Its single instance – a singleton.
Metaclass is where I'm getting lost, but it's definitely an Object, because it has isa. Metaclass has a list of method implementations (+methods) of its single instance – the Class.
When you write this code:
#interface MYObject : NSObject
+ (void)classMethod; // Stored in Metaclass
- (void)instanceMethod; // Stored in Class
#end
You are creating a pair: Class and Metaclass.
Oh, and what is a class of Metaclass? A Root Metaclass!
And what is a class of the Root Metaclass? The Root Metaclass itself!
But then where isa of Metaclasses points to? To our old friend NSObject. Too meta, right?
Related
I am reading some book about objective C ,and they say there that NSNumber is an abstract superclass of many subclasses that we can use .
So, "when we call a method in NSNumber, the appropriate subclass is used" .
This is not going with some other rule that i know :
if superclass A, has subclass B , and you calling a method in the super class A , that is in the subclass B, you can't do that- because inheritance is working all the way up and not down.
So, how is that the superclass (abstract) class- NSNumber, is using its subclass methods ??
What is the hierarchy here ?
Thanks .
It's done through class cluster pattern.
From documentation:
The abstract superclass in a class cluster must declare methods for
creating instances of its private subclasses. It’s the superclass’s
responsibility to dispense an object of the proper subclass based on
the creation method that you invoke—you don’t, and can’t, choose the
class of the instance.
Whenever you create number with some factory method, like +numberWithInt: the factory returns instance of concrete subclass. Afterwards, when you call something like -stringValue: this selector is sent to instance of concrete NSNumber subclass - int in this case.
So, NSNumber factory methods actually does not return NSNumber objects - they return concrete subclasses. Same is true for other Cocoa class clusters - NSArray, NSDictionary, NSSet.
In effect there are classes NSDoubleNumber, NSLongLongNumber, NSIntegerNumber, etc, (made-up names) and you get the appropriate one. But as with all subclassing, if you then call a method of the object via it's superclass type it will respond, invoking the class-specific method appropriate to that instance.
Objective-C muddles things slightly, since if you ask what the class is it won't return "NSDoubleNumber" or whatever but instead returns an essentially meaningless name for the whole cluster, or for a particular subdivision of it.
The point is, you can treat the instances as objects of the single fictitious class "NSNumber" and never need to worry about which subclass you actually have.
(BTW, similar things are true of NSArray, NSDictionary, and a number of other classes.)
Please observe this method declaration:
NSString *NSStringFromClass(Class aClass);
I want to understand the Class class, but I can't find docs about it because I don't know how to create a good enough regular expression and google with it. The fact that the class name is Class and not NSClass makes me think Class is not a real class (like java.lang.Class). But, I don't know, and so I want to research this. But, I can't find docs.
If I need to ask a specific question:
is "Class" in obj-c a real class? what are its methods and properties?
Quoting from Cocoa with Love
Every object has a class. This is a fundamental object-oriented concept but in Objective-C, it is also a fundamental part of the data. Any data structure which has a pointer to a class in the right location can be treated as an object.
In Objective-C, an object's class is determined by its isa pointer. The isa pointer points to the object's Class.
And as a proof of it, here's the declaration of id as a pointer to the objc_object struct.
typedef struct objc_object {
Class isa;
} *id;
So here we get to the point. What is a Class?
Let's look at the definition
Class is defined as follows (it may actually vary depending on the runtime, but let's keep it simple)
struct objc_class {
Class isa;
}
typedef struct objc_class *Class;
As you can see a Class has a isa pointer as well. It looks suspiciously like the objc_object definition and the reason is simple: Class is in fact an object.
But what is the class of a Class? It's - by definition - a meta-class.
According to the same source (in bold the part that tackles your question directly),
The meta-class, like the Class before it, is also an object. This means that you can invoke methods on it too. Naturally, this means that it must also have a class.
All meta-classes use the base class' meta-class (the meta-class of the top Class in their inheritance hierarchy) as their class. This means that for all classes that descend from NSObject (most classes), the meta-class has the NSObject meta-class as its class.
Following the rule that all meta-classes use the base class' meta-class as their class, any base meta-classes will be its own class (their isa pointer points to themselves). This means that the isa pointer on the NSObject meta-class points to itself (it is an instance of itself).
For further reading on the subject, here's another great explanation by Greg Parker.
Before I start let me ask that in objective-c 2.0 you can have a baseclass pointer reference a subclass object?
If so is there something similar to c++ virtual member functions in objective-c.
For instance if a subclass object gets called from a baseclass pointer, will it call the subclass method (it properly overrides the base class method)? Would it be forced as well like Java or does the programmer have control over it?
Edit: would it be possible to assign any pointer type to another, what is the limit? Ex:
Can you say
Subclass *s = ...
Baseclass *b= s
Or can it only be done by allocation?
You can have a base class pointer hold onto the value of a subclass instance's address. So
Subclass s* = /* get an object instance */
Baseclass b* = s;
is possible (this doesn't have to be during init). There isn't a limit.
The "virtual method" like functionality is like Java, so every method is virtual so you don't have control over it (e.g. the subclass method is always called). Messages being sent to objects have, in effect, late binding.
See Implement a pure virtual method in Objective-C .
okay, so I understand that an object is an instance of a class that must be allocated and initialized, but are classes themselves objects?
I know when you create a new class it is an instance of something else, like NSObject. So, if this makes it a class, then objects can hold not only variables and methods, but other objects as well, right?
Sorry, this is probably really basic, but I am reading two books about cocoa and xcode and this point is a little unclear (probably because of my lack of experience in other languages).
Here is a pretty good explanation of the matter by Greg Parker
Quoting:
[...] Each Objective-C class is also an
object. It has an isa pointer and
other data, and can respond to
selectors. When you call a "class
method" like [NSObject alloc], you are
actually sending a message to that
class object.
Since a class is an object, it must be
an instance of some other class: a
metaclass. The metaclass is the
description of the class object, just
like the class is the description of
ordinary instances. In particular, the
metaclass's method list is the class
methods: the selectors that the class
object responds to. When you send a
message to a class - an instance of a
metaclass - objc_msgSend() looks
through the method list of the
metaclass (and its superclasses, if
any) to decide what method to call.
Class methods are described by the
metaclass on behalf of the class
object, just like instance methods are
described by the class on behalf of
the instance objects.
What about the metaclass? Is it
metaclasses all the way down? No. A
metaclass is an instance of the root
class's metaclass; the root metaclass
is itself an instance of the root
metaclass. The isa chain ends in a
cycle here: instance to class to
metaclass to root metaclass to itself.
The behavior of metaclass isa pointers
rarely matters, since in the real
world nobody sends messages to
metaclass objects. [...]
Further interesting reads:
Understanding the Objective-C Runtime by Colin Wheeler
(search for paragraph titled "So Classes define objects…")
What is a meta-class in Objective-C? by Matt Gallagher
The documentation says:
While not strictly a part of the
language, the isa pointer is required
for an object to work with the
Objective-C runtime system. An object
needs to be “equivalent” to a struct
objc_object (defined in objc/objc.h)
in whatever fields the structure
defines. However, you rarely, if ever,
need to create your own root object,
and objects that inherit from NSObject
or NSProxy automatically have the isa
variable.
While that sounds nice, I wonder how an root object would be created in Objective-C anyways?
This is for learning purposes. I just want to know this. I'd really like to see it.
It's actually a "trap" some people migrating from C# or Java style languages fall into. You simply don't specify a superclass when declaring your class i.e.
#interface MyNewRoot {
Class isa;
}
#end
vs
#interface MyObject : NSObject {
}
#end
In Java or C# these would be equivalent (in the first case the compiler would assume System.Object or java.lang.Object was the superclass), but in Objective-C no such default will be assumed, and hence a new root is created.
However you're now responsible for a number of features for your class that you typically take for granted (even simple things like memory management for allocating or destorying new instances etc). This is what the comment you quoted hints at when it talks about struct objc_object and the isa instance variable etc.