Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the basic knowledge of runtime in iOS development

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about the basic knowledge of runtime in iOS development, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

1. Run time

1.1 basic concepts: runtime

The concept of Runtime

Runtime, also known as runtime, is a set of low-level C language API, which is one of the internal cores of iOS. The OC code we usually write is based on it. For example:

You may not see its value above, but what we need to understand is that Objective-C is a dynamic language that does some work at run time rather than compile time. That is, there are many classes and member variables that we don't know when we compile, and at run time, the code we write is converted to complete and definite code to run.

Therefore, the compiler is not enough, we also need a runtime system (Runtime system) to process the compiled code. Runtime is basically written in C and Hub, which shows Apple's efforts to make dynamic systems efficient. Apple and GNU each maintain an open source version of Runtime, and both are trying to be consistent.

The role of Runtime

Objc interacts with Runtime systems on three levels:

Through the Objective-C source code

Methods defined by the NSObject class of the Foundation framework

By calling the Runtime library function directly

1.2 C expression of various basic concepts

In Objective-C, classes, objects, and methods are all structures of C, and we can find their definitions from objc/objc.h (objects, objc_object,id) and objc/runtime.h (related to other, classes, methods, method lists, variable lists, attribute lists, etc.).

① class

The class object (Class) is defined by the programmer and created by the compiler at run time, it does not have its own instance variables, it is important to note that the member variables and instance method list of the class belong to the instance object, but it is stored in the class object. Let's look at the definition of Class under objc/objc.h:

Class

Here I still want to recommend my own iOS development learning group: 680565220, the group is all learning ios development, if you are learning ios, editor welcome you to join, today's sharing of this case has been uploaded to the group file, everyone is a software development party, irregularly share practical information (only iOS software development related), including a 2018 of my own collation of the latest iOS advanced materials and advanced development tutorials

You can see that the class is represented by the Class type, which is a pointer to the objc_class structure type. Let's move on to the definition of the objc_class structure:

Objc_class

Parameter analysis

The isa pointer is an objc_class structure pointer of the same type as Class, and the pointer of the class object points to the class to which it belongs, that is, the metaclass. The class method of the class object is stored in the metaclass, and when accessing the class method of a class, the isa pointer is used to find the function pointer corresponding to the method in the metaclass.

The super_class pointer points to the parent class object that the class inherits, and super_class is NULL if the class is already the top-most root class (such as NSObject or NSProxy).

Cache: used to cache recently used methods. When a recipient object receives a message, it looks for an object that can respond to the message according to the isa pointer. In practical use, only some of the methods of this object are commonly used, and many methods are rarely or not used at all. In this case, if we traverse through methodLists every time a message comes, the performance is bound to be very poor. At this point, cache came in handy. After we call a method each time, the method will be cached in the cache list. The next time we call it, runtime will first look up the method in cache, and if cache does not, then go to methodLists to look for the method. In this way, the invocation of methods that are often used can improve the efficiency of the invocation.

Version: we can use this field to provide the version information of the class. This is very useful for object serialization, which allows us to identify changes in the layout of instance variables in different versions of class definitions.

Protocols: of course you can see the pointer to this objc_protocol_list. I will talk about the structure of objc_protocol_list later.

Get the class name of the class

The instance object is created when we operate on the class object alloc or new. In the process, we copy the member variables of the class to which the instance belongs, but not the methods defined by the class. When calling an instance method, the system will look for the method pointed to by the selector corresponding to the message in the method list of the class and the method list of the parent class according to the isa pointer of the instance. Similarly, let's take a look at the definition:

Objc_object

As you can see, this structure has only one isa variable that points to the class to which the instance object belongs. Any structure that starts with a pointer and points to a class structure can be thought of as an objc_object, and the most important feature of an object is that it can be sent a message. Alloc and allocWithZone of the NSObject class: the method uses the function class_createInstance to create the objc_object data structure.

In addition, our common id type, which is a pointer to the objc_object structure type. This type of object can be converted to any kind of object, similar to the role of the void * pointer type in the C language. It is defined as follows:

Id

A Metaclass is a class of class objects. Each class has its own metaclass, that is, the class pointed to by the isa pointer in the objc_class structure. The class method of Objective-C is the root cause of using metaclass because it stores the method called by the corresponding class object, that is, the class method.

When you send a message to an object, runtime looks for the method that sends the message in the list of methods of the class to which the object belongs, but when you send a message to the class, runtime looks in the list of meta class methods of that class. All meta class, including Root class,Superclass,Subclass 's isa, point to Root class's meta class, which forms a closed loop.

So as you can see from the figure above, when sending a message to an instance object or class object, the rule for finding a method list is:

When sending a message to an instance object, the message is looking for a list of methods (instance methods) of the object's class.

When sending a message to a class object, the message is looking for a list of methods (class methods) for the metaclass of the class.

A metaclass, like the previous class, is also an object and can also call its methods. So this means that it must also have a class. All metaclasses use the root metaclass as their class. For example, the metaclass of all subclasses of NSObject will take the metaclass of NSObject as their class.

According to this rule, all metaclasses use the root metaclass as their class, and the metaclass of the root metaclass is itself. That is, the isa pointer to the metaclass of the base class points to himself.

Operation function

Super_class and meta-class

In Objective-C, attributes (property) and member variables are different. So, what is the nature of attributes? What's the difference between it and member variables? To put it simply, an attribute is a member variable with an access method added, that is:

@ property = ivar + getter + setter

Therefore, each time we define a @ property, we add the corresponding ivar, getter, and setter to the class structure objc_class. Specifically, the system adds a description of member variables to objc_ivar_list, and then adds descriptions of setter and getter methods to methodLists. The following objc_property_t is the type of declared property and is a pointer to the objc_property structure.

Examples of usage

In addition, there is a list of objc_property_attribute_t structures for properties, and the objc_property_attribute_t structure contains name and value

Objc_property_attribute_t

Common attributes are as follows:

Attribute type name value: t value: variation

Encoding type name value: C (copy) & (strong) W (weak) empty (assign) and other value: none

Non / atomic name value: empty (atomic) N (Nonatomic) value: none

Variable name name value: v value: variation

For example

⑤ member variable

Ivar: the instance variable type, which points to the objc_ivar structure

Pointer

Ivar

In objc_class, the information of all member variables and attributes is placed in the linked list ivars. Ivars is an array in which each element is a pointer to Ivar (variable information).

Objc_ivar_list

Among them

Method name is of type SEL

The method type method_types is a char pointer that stores the parameter type and return value type of the method

Method_imp points to the implementation of a method, which is essentially a function pointer.

In short, Method = SEL + IMP + method_types is equivalent to establishing a mapping between SEL and IMP.

Operation function

The definition of objc_selector is not found directly in the source code. From some books and Blog, we can understand SEL as a char* pointer.

Exactly what this objc_selector structure is depends on the runtime that uses GNU or Apple. In Mac OS X, SEL is actually mapped to a C string, which can be regarded as the name of the method, and it does not point to the specific method implementation (the IMP type is).

For all classes, as long as the method name is the same, the resulting selector is the same.

Operation function

It is actually a function pointer to the first address of the method implementation. By obtaining IMP, we can skip the message passing mechanism of runtime and directly execute the function implementation pointed to by IMP, thus eliminating a series of lookup operations in the process of runtime message delivery, which is more efficient than sending messages directly to objects. Of course, it must be noted that this method is only suitable for very special optimization scenarios, such as calling a method in a large number of cycles in efficiency-sensitive scenarios.

Operation function

The cache field in the objc_class structure is mentioned above, which is used to cache the called method. This field is a pointer to the objc_cache structure, defined as follows:

Cache

The field description of the structure is as follows:

Mask: an integer that specifies the total number of cache bucket allocated. During the method lookup process, Objective-C runtime uses this field to determine the index location of the starting linear lookup array. The pointer to the method selector does an AND bit operation with the field (index = (mask & selector)). This can be used as a simple hash hashing algorithm.

Occupied: an integer that specifies the total number of cache bucket actually occupied.

Buckets: an array of pointers to Method data structures. This array may contain no more than mask+1 elements. It should be noted that the pointer may be NULL, indicating that the cache bucket is not occupied, and the occupied bucket may be discontiguous. This array may grow over time.

⑪ protocol linked list

In the structure of the previous objc_class, there is a parameter to the protocol list, which is used to store the formal protocol that declares compliance.

Objc_protocol_list

two。 Method invocation process

The objc_msgSend () Tour series of articles summarize the following process through the analysis of the assembly source code of objc_msgSend:

2.1 method invocation process

Check whether selector needs to be ignored

Check whether target is nil, if it is nil, cleanup directly, and then return

Find IMP according to selector in the Class of target

2.2 the process of finding IMP:

Look for (cache methodLists) in the current class method cache

Found to jump to the corresponding method implementation, did not find to continue to execute

Find (methodLists) from the current class method list, find the addition to the cache list, and then jump to the corresponding method implementation; no further execution is found

Look in superClass's cache list and method list until the base class is found

If you cannot find IMP in the above steps, enter the process of dynamic message processing and message forwarding. For more information, please follow the official account of Wechat: programmer Daniel!

We can find the above process of finding IMP in the official source code of objc4. The corresponding code is as follows:

Objc-class.mm

3. Runtime related API

3.1 methods defined through the NSObject class of the Foundation framework

Most of the classes in Cocoa programs are subclasses of the NSObject class, so they all inherit the behavior of NSObject. (the exception is the NSProxy class, which is an abstract superclass)

In some cases, the NSObject class simply defines the template that accomplishes something and does not provide the required code. For example, the-description method, which returns a string representation of the contents of the class, is mainly used to debug programs. The NSObject class does not know the contents of the subclass, so it just returns the name of the class and the address of the object, and the subclass of NSObject can be reimplemented.

There are also NSObject methods that can get information from the Runtime system and allow objects to self-check. For example:

The-class method returns the class of the object

-isKindOfClass: and-isMemberOfClass: methods check whether the object exists in the inheritance system of the specified class (whether it is a member variable of its subclass or parent class or the current class)

-respondsToSelector: check whether the object can respond to the specified message

-conformsToProtocol: check whether the object implements the method of the specified protocol class

-methodForSelector: returns the address of the specified method implementation.

A common example:

Id and void * convert API: (_ _ bridge void *)

When ARC is valid, id and void * can be converted to each other through (_ _ bridge void *) conversion. Why switch? This is because the parameters of objc_getAssociatedObject require it. Take a look at its API first:

As you can see, the key of this "property name" must be a parameter of type void *. So it needs to be converted. With regard to this transformation, here is an example of the transformation:

4. Operational Guide at run time

The above API is not for everyone to memorize, but for reference, when you need to use it. Because these principles and API are useless, we need to look back and understand them after the actual combat.

After reading the above, do you have any further understanding of the basic knowledge of runtime in iOS development? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report