Learn about iOS runtime

Source: Internet
Author: User

First, IOS runtime principle

For the runtime mechanism, the information found on the Internet is probably how to use these things, and to see the implementation of the Runtime.h header file, of course, this is a good way to learn, but, in fact, we still do not know the runtime is compiled into the C + + language after what to do?
Find a Daniel to the information, immediately to the runtime have a certain understanding!

We casually write a small program, the code is as follows:
The person class header file is as follows,

<!-- lang: cpp -->#import <Foundation/Foundation.h>

@interface Person:nsobject

@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) int age;

@end

MAIN.M files are as follows

<!-- lang: cpp -->int main(int argc, const char * argv[])

{

Person *p = [[Person alloc] init];NSString *str = @"zhangsan";p.name = str;// p.name 等价于[p setName:str];p.age = 20;return 0;

}

Then we open the terminal, locate the CD to the file directory at the command line, and then enter:

clang -rewrite-objc main.m 

command can compile main.m into C + + code, change to a different file name, will generate different C + + code
This is to generate the main.cpp this C + + file, open the file code
Look at the bottom main function of the main.cpp,
This way we can see how the underlying implementation works!

At this point, we need to know these methods:
Objc_msgsend can send messages to objects
Objc_getclass ("person") can get the object to the specified name
Sel_registername ("Alloc") methods that can be called to an object

By looking at the C + + code, we come to the conclusion that:
Use the Objc_msgsend function to send the method Sel_registername obtained to the object instantiated by the Objc_getclass function
Such a message
Code is for people to see, incidentally let the machine realize the function. In the process of routine development, we should use less runtime,

When will the runtime be used?
Runtime Application Timing:
1> when you need very high performance development, use runtime, note: OC code has not been able to meet performance requirements
2> when we are curious about the implementation of the system, we can use Clang to decompile C + + to see the underlying implementation mechanism!

Finally, I know I wrote this blog may not be very good, or readers think there is something wrong, I hope to point out, we progress together!

The project is to explain the runtime's underlying implementation principle, if you want to know how the runtime is used, you can view the runtime.h header file View!
The following is the runtime mechanism method of some of the use of methods introduced, I hope it is useful for everyone!
Related Technical documents: HTTP://WWW.TUICOOL.COM/ARTICLES/UIMINM
http://blog.csdn.net/lengshengren/article/details/17764135

Ii. full interpretation of runtime mechanism of runtime

We have already talked about a runtime principle, now this article is mainly about what the runtime is and how to use! Hope to help the reader!

First of all, the first question,
1 "Runtime implementation of the mechanism is what, how to use, generally used to do?"
I'm not going to mealy you with this question, just tell everyone,
Runtime is a relatively low level of pure C language API, belongs to 1 C language Library, contains a lot of the underlying C language API.
In the OC code that we usually write, the program runs the process, in fact, it turns into the runtime's C language code, runtime is OC's behind-the-scenes workers
For example, in the following method of creating an object,
Example:
Oc:
[[Mjperson alloc] init]
Runtime:
Objc_msgsend (Objc_msgsend ("Mjperson", "Alloc"), "Init")

A second question
What does runtime use for?? Where do you use them? How to use it?
Runtime is the bottom of the OC and can perform some very low-level operations (with OC is not realistic, bad implementation)

    • Dynamically create a class during the program's run (for example, the KVO implementation)

    • Dynamically add properties \ Methods to a class while the program is running, modify property values \ Methods

    • Traverse all member variables (properties) of a class \ All methods
      For example: We need to archive the properties of a class when the properties are particularly large, when we will write a lot of corresponding code, but if you use the runtime can be set dynamically!
      For example, the PYPerson.h file looks like this

      Import

@interface Pyperson:nsobject
@property (nonatomic, assign) int age;
@property (nonatomic, assign) int height;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age2;
@property (nonatomic, assign) int height2;
@property (nonatomic, assign) int age3;
@property (nonatomic, assign) int height3;
@property (nonatomic, assign) int age4;
@property (nonatomic, assign) int height4;

@end

and the contents of the PYPERSON.M implementation file are as follows

<!-- lang: cpp -->#import "PYPerson.h"
Import

@implementation Pyperson

  • (void) Encodewithcoder: (Nscoder ) encoder
    {
    unsigned int count = 0;
    Ivar
    ivars = Class_copyivarlist ([Pyperson class], &count);

    for (int i = 0; i<count; i++) {

    // 取出i位置对应的成员变量Ivar ivar = ivars[i];// 查看成员变量const char *name = ivar_getName(ivar);// 归档NSString *key = [NSString stringWithUTF8String:name];id value = [self valueForKey:key];[encoder encodeObject:value forKey:key];

    }

    Free (ivars);
    }

  • (ID) Initwithcoder: (Nscoder *) decoder
    {
    if (self = [super init]) {

     unsigned int count = Span class= "Hljs-number" >0;ivar *ivars = Class_copyivarlist ([Pyperson class], &count); for (int i = 0; i<count; i++) { Span class= "hljs-comment" >//remove the member variable corresponding to the i position Ivar Ivar = ivars[i]; //View member variables const char *name = Ivar_ GetName (Ivar); //archive nsstring *key = [NSString Stringwithutf8string:name]; id value = [Decoder decodeobjectforkey:key]; //set to member variable body [self setvalue:value Forkey:key];} Free (ivars);                

    }
    return self;
    }

@end

So we can see the case of the archive and the file is actually written by runtime.

Learning, the runtime mechanism must first understand the following questions
1 Related header files and functions
1> header File


    • With the header file, we can view the various methods in the runtime!

2> related applications

    • Nscoding (archive and file, use Runtime to traverse all properties of Model objects)
    • Dictionary –> model (use Runtime to traverse all properties of the model object, remove the corresponding value from the dictionary based on the property name, set to the properties of the model)
    • KVO (using runtime to generate a class dynamically)
    • For packaging frames (how to change them)
      That's the way we use the runtime mechanism.

3> Correlation function

    • Objc_msgsend: Sending a message to an object
    • Class_copymethodlist: Traversing all methods of a class
    • Class_copyivarlist: Traversing all member variables of a class
    • Class_ .....
      This is the function we must know to learn the runtime!

4. Essential Knowledge
1> Ivar: Member variable
2> method: Member Methods
From the example above we see the member variables we define, and if you are dynamically creating methods, you can use method

Third, runtime practical application

Runtime: Run-time mechanism
The first thing to understand:
1. What is
1> runtime is a relatively low level of pure C language API, belongs to 1 C language Library, contains a lot of the underlying C language API
2> usually write the OC code, in the process of running the program, in fact, eventually turned into the runtime's C language code, runtime is OC's behind-the-scenes workers
Here is an example, as mentioned in the previous article! We can see the underlying file by compiling it into C language.
Oc:
[[Person alloc] init]
When the person object above is created,
Runtime:
Objc_msgsend (Objc_msgsend ("person", "alloc"), "Init")

And the above part just understand the most basic principle, then runtime and what is the deeper use of it?
2.runtime used? What's the use? What can I do for you?
What we need to understand is:
1> runtime is the lower level of OC, can perform some very low-level operations (with OC is not realistic, bad implementation can be achieved through runtime)

    • Dynamically create a class during the program's run (for example, the KVO implementation)
    • Dynamically add properties \ Methods to a class while the program is running, modify property values \ Methods
    • Traverse all member variables (properties) of a class \ All methods

3. Related header files and functions
1> header File


    • Opening the header file, we found a lot of methods, but the most we used is the following function,
      Related functions
    • Objc_msgsend: Sending a message to an object
    • Class_copymethodlist: Traversing all methods of a class
    • Class_copyivarlist: Traversing all member variables of a class
    • Class_ .....

Of course, when it comes to using these things, we first have to understand something,
Essential knowledge
1> Ivar: Member variable
2> method: Member Methods

2> Runtime related practical applications

    • Nscoding (archive and file, use Runtime to traverse all properties of Model objects)
    • Dictionary –> model (use Runtime to traverse all properties of the model object, remove the corresponding value from the dictionary based on the property name, set to the properties of the model)
    • KVO (using runtime to generate a class dynamically)
    • For packaging frames (how to change them)

The code below is a piece of code that uses the runtime mechanism when archiving a file, so you don't have to assign a value to each property,

<!-- lang: cpp -->- (void)encodeWithCoder:(NSCoder *)encoder

{

unsigned int count = 0;Ivar *ivars = class_copyIvarList([PYPerson class], &count);for (int i = 0; i<count; i++) { // 取出i位置对应的成员变量 Ivar ivar = ivars[i]; // 查看成员变量 const char *name = ivar_getName(ivar); // 归档 NSString *key = [NSString stringWithUTF8String:name]; id value = [self valueForKey:key]; [encoder encodeObject:value forKey:key];}free(ivars);

}

    • (ID) Initwithcoder: (Nscoder *) decoder
      {
      if (self = [super init]) {
      unsigned int count = 0;Ivar *ivars = class_copyIvarList([PYPerson class], &count);for (int i = 0; i<count; i++) { // 取出i位置对应的成员变量 Ivar ivar = ivars[i]; // 查看成员变量 const char *name = ivar_getName(ivar); // 归档 NSString *key = [NSString stringWithUTF8String:name]; id value = [decoder decodeObjectForKey:key]; // 设置到成员变量身上 [self setValue:value forKey:key];}free(ivars);
      }
      return self;
      }

Learn about iOS runtime

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.