(turn) detailed Objective-c's Meta-class

Source: Internet
Author: User
Tags instance method

Transfer from http://blog.csdn.net/windyitian/article/details/19810875

A relatively simple English, the focus is to explain meta-class. Translate, deepen understanding.

Original title: What's a meta-class in objective-c?

Original address: http://www.cocoawithlove.com/2010/01/what-is-meta-class-in-objective-c.html

This article will explore a relatively unfamiliar concept in objective-c-meta-class. Each class in OC will have a meta class associated with it, but you will almost never use it directly, and they are always shrouded in a veil of mystery. The author will dynamically create a class for the runtime to draw, through the analysis of the created class pair to figure out what exactly meta-class is and more in-depth understanding of its meaning for objects and classes in OC.

To create a class at run time

The following code demonstrates that the runtime creates a nserror subclass and adds an instance method to it:

[CPP]View Plaincopy
    1. Class Newclass =
    2. Objc_allocateclasspair ([Nserror class], "Runtimeerrorsubclass", 0);
    3. Class_addmethod (Newclass, @selector (report), (IMP) reportfunction, "[email protected]:");
    4. Objc_registerclasspair (Newclass);



The function reportfunction is the concrete implementation of the added instance method, as follows:

[CPP]View Plaincopy
  1. void Reportfunction (id self, SEL _cmd)
  2. {
  3. NSLog (@"This object was%p.", self);
  4. NSLog (@"Class is%@, and Super are%@.", [self class],[self superclass]);
  5. Class Currentclass = [self class];
  6. For ( int i = 1; i < 5; ++i)
  7. {
  8. NSLog (@"Following the Isa pointer%d times gives%p", I,currentclass);
  9. Currentclass = Object_getclass (Currentclass);
  10. }
  11. NSLog (@"NSObject ' s class is%p", [NSObject class]);
  12. NSLog (@"NSObject's meta class is%p", Object_getclass ([NSObject class]);
  13. }


It seems like everything is simple, and it only takes three steps to create a class at run time:
1. Allocate space for "class pair" (using Objc_allocateclasspair).
2. Add methods and members for the created class (the previous example adds a method using Class_addmethod).

3. Register the class you created to make it available (use Objc_registerclasspair).

The reader is expected to ask immediately: what is "class pair"? Objc_allocateclasspair returns only one value: Class. So where's the other half of the pair?

Yes, I guess you already guessed that the other half is Meta-class, which is the title of this essay, but to explain what it is, why it is needed, and to account for the background of the object and class of OC.

Why does a data structure become an object?

Each object will have a class that it belongs to. This is the basic object-oriented concept, but in OC, this is valid for all data structures. Any data structure, as long as it has a pointer to a class in the right place, it can be considered an object.
In OC, which class an object belongs to, is pointed to by its Isa pointer. This ISA pointer points to the class to which this object belongs.

In fact, the definition of an object in OC looks like this:

[CPP]View Plaincopy
    1. typedef struct Objc_object {
    2. Class Isa;
    3. }*id;


This definition shows that any data structure with a pointer to class as the first member can be considered a objc_object.

The most important feature is that you can send a message to any object in OC, like this:

[CPP]View Plaincopy
    1. "@" StringValue"writetofile:@"/file.txt atomically:yes encoding:nsutf8stringencoding Error:NULL];

The principle of operation is that when you send a message to an OC object (@ "StringValue" above), the runtime library will find the class that this object belongs to, based on the object's Isa pointer (for example, the Nscfstring class is found). This class contains a list of all instance methods and a pointer to superclass so that an instance method of the parent class can be found. The run-time library looks for a method that conforms to this selector (for example, this selector is "WriteToFile:atomically:encoding:error") in the method list of the class and the method list of the parent class (s). Run this method when it is found. The key point is that the class defines the message you send to the object.


What is Meta-class?


At this point, you may already know that an OC class is actually an object, meaning that you can send a message to a class.
nsstringencoding defaultstringencoding = [NSString defaultstringencoding];
In this example, defaultstringencoding is sent to the NSString class. Because each OC class is itself an object. This means that the data structure of class must also be fully compatible with Objc_object at the binary level, starting with the ISA pointer. Then the next field of a class structure must be a pointer to super class (or nil, for the base class).
There are many ways to define a class, depending on the version of your runtime library, but either way, they take an Isa as the first field, followed by the superclass field.

[CPP]View Plaincopy
[CPP]View Plaincopy
    1. typedef struct Objc_class *class;
    2. struct objc_class{
    3. Class Isa;
    4. Class Super_class;
    5. /*followed by runtime specific details...*/
    6. };

In order for a class method to be called, the ISA pointer for this class must point to a class structure that contains these class methods.
This leads to the concept of Meta-class: Meta-class is the class of a class object.
Simply explained below:
When you send a message to an object, runtime looks in the list of methods for the class to which the object belongs.
When you send a message to a class, runtime looks in the list of Meta-class methods for that class.
Meta-class is important because it stores all the class methods of a class. Each class will have a separate meta-class, because the class methods of each class are not nearly identical.


What is the class of Meta-class?


Meta-class, like class, is also an object. You can still send a message call function to it, naturally, Meta-class will also have an Isa pointer pointing to its owning class. All meta-class Use the meta-class of the base class as their owning class. In particular, any meta-class under the NSObject inheritance system uses NSObject's Meta-class as the class to which they belong.
According to this rule, all meta-class use the meta-class of the base class as their class, and the Meta-class of the base class belongs to itself, that is, the base class's Meta-class Isa pointer points to itself. (translation: Perfect closed-loop)


Inheritance of classes and Meta-class


Just as a class uses the Super_class pointer to point to its parent class, Meta-class's Super_class points to Meta-class of the super_class of the class. has been traced back to the base class's Meta-class, its super_class will point to the base class itself. (translation: All things in the final)
As a result, instances, classes, and Meta-class in the entire inheritance system derive from the base class in the inheritance system. For NSObject inheritance system, NSObject's instance method is effective for all instances, classes and meta-class in the system, and NSObject class method is effective for all classes and meta-class in the system.
The words are always confusing, and Greg Parker gives a wonderful atlas to show these relationships:
Click to open link


Experimental results show that:


To confirm the above, let's look at the output from the reportfunction in the opening code. The purpose of this function is to print along the ISA pointer.
In order to run erportfunction, we need to create an instance and call the report method.

[CPP]View Plaincopy
    1. ID instanceofnewclass = [[Newclass alloc]initwithdomain:@"Some Domain" code:0 Userinfo:nil];
    2. [Instanceofnewclass performselector:@ "report)];
    3. [Instanceofnewclass release];



Because we do not declare the report method, we use Performselector to make the call, thus avoiding compiler warnings.

The Reportfunction function then retrieves along the ISA to tell us what the Class,meta-class and Meta-class classes are like:

Note: Reportfunction uses Object_getclass to get the class that the ISA pointer points to, because the ISA pointer is a protected member and you cannot directly access the ISA pointers of other objects. Reportfunction does not use the class method because calling this method on a class object does not get meta-class, it simply returns the class. (So [NSString class] Simply returns the NSString class, not NSString's meta-class]
The following is the output of the program:

[CPP]View Plaincopy
[CPP]View Plaincopy
    1. This object is 0x10010c810.
    2. Class is Runtimeerrorsubclass, and super is nserror.
    3. Followingthe Isa pointer 1times gives 0x10010c600
    4. Followingthe Isa pointer 2times gives 0x10010c630
    5. Followingthe Isa pointer 3times gives 0x7fff71038480
    6. Followingthe Isa pointer 4times gives 0x7fff71038480
    7. NSObject ' s class is 0x7fff710384a8
    8. NSObject ' s meta class is 0x7fff71038480

Observe the addresses obtained through ISA:
The address of the object is 0x10010c810.
The address of the class is 0x10010c600.
The Meta-class address of the class is 0x10010c630.
The class address of the Meta-class class is 0x7fff71038480. (i.e. Nsojbect's Meta-class)
The class address of the NSObject Meta-class is itself.
The values of these addresses are not important, and it is important that they illustrate the entire process of meta-class from class to Meta-class to NSObject discussed in the article.


Conclusion:


Meta-class are classes of class objects, each of which has its own separate meta-class. All class objects do not belong to the same meta-class.
Meta-class to ensure that the class object has all instances and class methods of the base class in the inheritance system, as well as all intermediate class methods in the inheritance system. For all classes under the NSObject inheritance system, nsobject instance methods and protocol methods are valid for both them and their Meta-class objects.
All Meta-class use the base class's meta-class as their base class, as are the Meta-class for the top-level base class, except that it points to itself.

(turn) detailed Objective-c's Meta-class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.