IOS nsruntime mechanism

Source: Internet
Author: User

What is Objective-c runtime?

Simply put, the OBJECTIVE-C runtime is a C library that implements the Objective-c language. objects can be represented in the structure of the C language, whereas methods (methods) can be implemented with C functions. In fact, they did almost as well, plus some extra features. Once these structures and functions are encapsulated by the runtime function, OBJECTIVE-C programmers can create, inspect, modify classes, objects, and their methods while the program is running.

In addition to encapsulation, the OBJECTIVE-C Runtime Library is also responsible for locating the final execution code of the method. When the program executes [object DoSomething], the method is not directly found and called. Instead, a message is sent to the object (here, we usually call it the recipient). The runtime library gives a chance for the object to decide what response to make based on the message. Alan Kay repeatedly emphasizes that message passing (message-passing) is the most important part of Smalltalk, not an object:

I am very sorry that I have created the word "object" before on this topic, and many people are now flocking to this concept.

In fact, the more important idea here is "message command" (messaging), which is the core content of Smalltalk (there are still some content not yet complete). A short word in Japanese is called "Ma", which is used to denote something between two objects, and the word closest to it in English may be "interstitial". The key to building a large and scalable system is to design the way it communicates between its modules, rather than focusing on its internal properties and behavior.

In fact, in an article that introduces Smalltalk virtual machines, this programming technique is called message delivery or messaging paradigm. "Object-oriented" is often used to describe memory management systems.

The word OBJC runtime is used in speeches and articles, and it appears to be only one, in fact there are many runtime libraries. Although they all support object introspection and message reception, they have different features and implementations (for example, the same message is sent, Apple's runtime is done in one step, and the GNU runtime queries the messages and then executes the found function in two steps). All of the following discussions are based on Apple's latest runtime library (the version of Apple at OSX 10.5 and iOS).

In that speech, I decided to study the functions of some areas of the runtime library. I found something that I wanted to get to know better, and then made it into a question-and-answer form to make my speech.

Dynamically creating classes

How to implement Key-value observing?

KVO the key to implementing the observer pattern is that it surreptitiously changes the class of the object being observed, and after it subclasses the original class, it is able to customize the method of the object to invoke the callback method of KVO. This is done through objc_duplicateclass, but unfortunately, this method is not public and we cannot invoke it privately.

All roads lead to Rome, but in addition to Objc_duplicateclass, there are other ways to implement observer patterns by using secret subclasses, such as creating and registering "class pair." So what is class pair? For objective-c classes, there is a pair of class objects to define it: Class object defines an instance method of this class, and Metaclass defines the classes method of this class. So each class is actually a single case of its metaclass.

This code shows how the Observer pattern works. When you add an observer to an object, the object first checks to see if it can be observed, and if it does, it will create a new class, replace the method of the original class with our own-dealloc, as well as the-class method, similar to the Kvo object, when you access the class name of the object being observed, It returns the original class name, not the newly generated class.

After the class is created, we need to add a setter method to the property according to Key-value coding: This setter method takes the value before the property modification and the modified value, and then calls the block form of the callback function, and tells the Observer the two values. The block can be called asynchronously, according to our wishes.

Note that-addobserverforkey:withblock: Uses S object_setclass () to replace the class of the observed object with the newly formed class. The main purpose of this is to change the way the message is transformed into a method, but it takes great care that the original class and the new class must have the same member variable layout. Because member variables are also accessed with runtime, modifying the class of an object may cause the runtime to not find the corresponding variable.

We were having trouble storing the observers ' collections because there was no place to save them. Adding member variables to the Observerpattern class does not work because there is no object that generates this class at all. The member variable of the observed object is its original class, and it does not consider these observers.

OBJECTIVE-C runtime helped us get out of this dilemma by introducing associated objects. In runtime, in theory, all objects can have dictionaries that contain other objects. By associated references, the observed objects can store and access their observers without the need for additional member variables.

If you run multiple times, you will find that Observerpattern is still a bit of a glitch. Because the observer callback is called asynchronously, the Observer

The changed events received are also chaotic. This means that the observer cannot actually distinguish what the final state of the observed attribute is, and the new value in the callback may have been modified already. I'm doing this to illustrate that calling callbacks synchronously in KVO is actually a useful feature, not a bug.

Creating objects

What are those extra bytes for?

When you create a Objective-c object, runtime allocates a little extra space after the instance variable storage area. What is the purpose of this? You can get the space start pointer (with Object_getindexedivars), and then you can index the instance variable (ivars). Well, I'll use a custom array to illustrate the usefulness of index Ivars.

Let's create an array! Two things can be seen from this simplearray: the most obvious is that it uses the cluster pattern. When using the +alloc method to return an object, the object is normally allocated with all memory, but in this case, the +alloc does not know how much memory is needed. Only if-initwithobjects:count is called: After that, it is possible to calculate how much memory this array needs based on the number of objects in the array, so +alloc simply returns a placeholder, and the real array object is assigned and returned only after initialization.

Maybe you ask why we use clusters to make things so complicated, use calloc () to allocate a chunk of the appropriate cache, and then put those object pointers inside. The answer is that you want to use the locality principle to improve access performance. From the design of arrays we can see that each time an array pointer is accessed, there is a great chance of accessing the cache pointer, so putting them side-by in memory means finding one of them is finding another.

Message distribution

How do messages be forwarded?

Objective-c one of the powerful features is that an object does not need to implement a method, although it declares the selector (selector) at compile time. But it can then determine the method implementation at run time, or forward these messages to other objects, or make exceptions, or do something else. But some aspects of this feature have been bothering me: message forwarding (msg forwarding) calls-forwardinvocation: And then passes in a Nsinvocation object. But this nsinvocation class is defined in the Foundation library, does it mean that runtime work requires foundation coordination?

I try to dig into the reason and find out that the answer is not what I think, runtime doesn't need to know foundation. Runtime will have the program define the forwarding function (forwarding functions), and when objc_msgsend () cannot find the implementation of the selector, that forwarding function is called. As soon as the program starts, Corefoundation will-forwardinvocation: defined as a forwarding function.

Let's create a ruby! Of course it's not true. Ruby,ruby has a function called #method_missing, and when the object receives a message that it does not implement, the function is transferred, which is similar to Smalltalk's practice. Using Objc_setforwardhandler, we can also implement Ruby-like methodmissing in Objective-c classes: methods.

Summarize

OBJECTIVE-C runtime can effectively help us to add a lot of dynamic behavior to the program. Some developers, in addition to using method swizzling to help debug the program, do not use it in the actual program, but runtime programming does have a lot of features, which should be an important tool for practical application code writing.

Original address: http://blog.securemacprogramming.com/2013/12/by-your-_cmd/

Add some of my understanding below

Because OC is a run-time language, the type of the object is determined only when the program is running, and the method corresponding to the object is called. The runtime mechanism allows us to dynamically modify all the properties and methods of a class, an object, while the program is running.

The following is a simple way to use the runtime to convert a Dictionary object to a model. Of course, you may ask, I use KVO direct call Setvaluesforkeyswithdictionary: method, passed in a dictionary as quickly as possible to the dictionary to the model Ah, but this method has its drawbacks, only to traverse the model of all the member variables, The corresponding value is then removed from the dictionary by the member variable and the most secure assignment, otherwise the error occurs when the number of attributes in the model is different from the number of keys in the dictionary. Moreover, because runtime is a lower-level language, we write the OC code at run time, the compiler will first into the C and C + + code, and then execute, so the runtime mechanism, the performance of the program will be better. Having said so much, the following is a preliminary understanding of the power of the runtime.

First, we define a class

@interface person:nsobject{    cgfloat height;} @property (nonatomic, copy) NSString *name; @property (nonatomic, strong) NSNumber *age; @property (nonatomic, assign) int n o; @end

Then we use this class in other files, note that before using it, include #import <objc/message.h>

The following is a small piece of code to get to all the member variables in the class above

unsigned int outcount = 0;    Ivar *vars = Class_copyivarlist ([lender class], &outcount); Get to all member variable list        //traverse all member variables for    (int i = 0; i < Outcount; i++) {        Ivar Ivar = vars[i];//Remove member variable                of position I const char *propertyname = Ivar_getname (Ivar); Gets the variable name        const char *propertytype = ivar_gettypeencoding (Ivar);//Gets the variable encoding type        printf ("---%s--%s\n", PropertyName , propertyType);    }

Printing results:

---height--f[email protected] "nsstring" [email protected] "NSNumber"---_no--i, you can get the names and types of all the variables in a class by using the simple code above. The Object_setivar () method is then used to assign a value to a member variable for a specific object.

IOS nsruntime mechanism

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.