OC run-time Programming Guide

Source: Internet
Author: User
Tags print object

First, Introduction

The language of OC, as much as possible, defers some decisions from compilation and linking to runtime. It will handle things as much as possible 动态 . This means that the language requires not only a compiler, but also a runtime system to execute the compiled code. This runtime system plays a role in the language operating system of OC, which allows the language to run.

This tutorial explores how nsobject this class and how OC is interacting with the language and runtime system. In particular, how to load classes dynamically at runtime, based on the paradigm of a class, and pass to other objects. This tutorial will also show you how to find the running information of your object while your program is running.

The OC Runtime Programming Guide describes the data structures and functions supported by the OC Runtime Library. You can use these interfaces in your own programs to interact with the OC Runtime system. For example, you can add classes and methods at run time, or get information about all classes that have already been loaded.

This tutorial consists of the following sections:

    • Message passing mechanism
    • Dynamic loading mechanism
    • Message forwarding mechanism
    • Type encoding
    • declaring properties
Ii. version and platform of the runtime system

1. Version of the runtime system

(1) Different versions of OC Runtime systems exist under different platforms:

<a> legacy version of the runtime interface is described in the OC 1.0 version of the language.

The <b> now version is based on the OC 2.0 version of the language, which contains a series of new features.

(2) The difference between the two versions is mainly reflected in the following areas:

<a>  in the legacy version of the runtime system, if you change the instance variable of a class, you 必须重新编译 have all of its subclasses.

<b> in the current version of the fishy system, if you change the instance variable of a class, you 无需重新编译 have all of his subclasses.

2.   Platform

iphone applications and OS X 10.5+ based 64-bit applications are based on the current version of the runtime system.

Other applications (32-bit applications based on OS X) use the legacy version of the runtime system.

Iii. interacting with the runtime system

  The OC program and the runtime system can be clearly divided into 3个 different levels:

(1) through the OC source code.

(2) The method defined by the NSObject class in the underlying framework.

(3) Call the run-time method directly.

  1. Through the OC source code

  In most cases, the work of the runtime system will be done automatically in this scenario. You just have to write and compile the OC code to use it.

  When you compile code that contains OC classes and methods, the compiler automatically implements data structures and function calls for language dynamic features. The data structure is created to capture the information of the class, class definition, and protocol declaration, as well as the method selectors in the source code, instance variable templates, and so on. The most important function of a run-time function is the function that is responsible for message passing, as described in the Message passing section. It is called through a message statement in the source code.

  2. Adoption of the method defined by the NSObject class in the underlying framework

  Most objects in the cocoa framework are subclasses of NSObject, so most objects inherit the methods defined by the NSObject class. (One notable exception is the Nsproxy class, which details the section on message delivery.) Thus, the NSObject method "regulates" the behavior of all his subclasses. However, in a few cases, NSObject does not define a template for how to do something, and it does not provide all the necessary code.

  For example, the NSObject class provides a description instance method for returning a string description of the class content. The main purpose of this method is to debug the--gdb Print object's command (PO instruction) to return the content that is the return value of this method. NSObject implements this method, but does not know exactly what the class contains, so it returns a string containing the class name and an in-memory address. All NSObject subclasses can implement this method and return a detailed description of the class, for example, the description of the Nsarray class inside the underlying framework returns a description of all the objects it contains.

  Some methods of NSObject classes simply query the runtime system information, which allows the object itself to check itself. For example , class is a method that queries the classes required for an object;Iskindofclass: and Ismemberofclass: is used to test the position of an object in the inheritance chain; Conformstoprotocol: is used to check whether an object implements a protocol, and similar methods give an object the ability to check its own information at run time.

3. Call the run-time method directly

The runtime system is a dynamic-link library that provides a range of public function interfaces and data structures that are located in/USR/INCLUDE/OBJC. Many of these functions allow you to use the pure C language to replicate what the compiler does when you write the OC code. Other forms of interface are the methods defined in the NSObject class. These methods can be used to implement other run-time interfaces to improve productivity. However, it is not necessary to program the OC language, but a few run-time functions are useful for OC programs in some special cases. These functions are described in the next step.

Iv. Message delivery mechanism

This chapter describes how message expressions are converted to Objc_msgsend method calls, and how you can make calls to methods by message names. Then explain how to take advantage of objc_msgsend and avoid dynamic bindings if needed.

  1.objc_msgsend function

  In the OC language, the message is not bound to the (c) method until run time, and the compiler translates a message expression.

becomes a call to a message-passing function, objc_msgsend. This function uses the message as 接收者 well 方法对应的选择器 as his most important parameter:

Any description passed in the message is also handled by the Objc_msgsend function:

  The message passing function provides all the necessary content for dynamic binding:

(1) first, it finds the procedure (method implementation) called by the selector. Because the same method may have different implementations in different classes, this exact invocation process relies on the class that the receiver belongs to.

(2) It then invokes the procedure, passing the recipient object (a pointer to its data), as well as the parameters defined in the message.

(3) Finally, it passes the return value of the procedure call as its own return value.

Note   : The compiler automatically calls the message-passing function. You 不应该 call the method directly in your own code.

The keywords used by the message-passing function are hidden in the structure of each OC class and object generated by the compiler compilation. Each class structure contains the following two essential elements:

    • A pointer to the parent object.
    • A class message is published . This table has 方法选择器 方法的内存地址 a link to the class and the entrance. For example, thesetorigin:: The selector of the method is associated with the method Setorigin:: implemented entry address, and display method selector is and display The address of the method is associated, and so on.

一个新对象一旦被创建,就会被分配内存,并且他的实例变量会被初始化。The first of these object variables is a pointer to the class structure that corresponds to the object. This pointer, called ISA, gives this object access to its class information and, through this class, accesses all of the class information it inherits from the class.

Note : In strict terms, the ISA pointer that the OC runtime relies on is not part of the language. In OC, an object needs to be "equal" to a objc_object struct defined in any form (defined in objc/objc.h). However, you hardly need to create your own root object yourself, inheriting objects from NSObject or Nsproxy to automatically include the ISA pointer.

These class elements and the object structure are illustrated by a picture.

When a message is passed to an object, the message passing function finds its class structure along the object's Isa pointer to find the method selector as well as the message sub-publication. If the method selector cannot be found, the message-passing function goes back to finding the pointer to its parent class to find the method selector and the message to be published, a process known to find the root of the inheritance tree. Once the corresponding selector is found, the function invokes the corresponding method address in the distribution table, passing the data structure of the fly receiver object.

This is how the runtime chooses method calls, or, in the case of object-oriented programming, the way in which messages are dynamically bound to methods.

To speed up the process of this message invocation. The runtime caches the selectors they used and the corresponding method addresses. These caches are cached separately for each class, and of course, this includes the methods that it defines itself and the methods that inherit from the parent class. Before a search is published, the message-passing route checks the cache of the receiving class for the received message (based on the theory that it is likely to do the next time if it is done once). If the message selector exists in the cache, message delivery is only a little slower than a direct function call. Once a program has been running long enough to "warm up" his cache, almost all messages sent may be cached. The cache is dynamically growing according to the call of the program to run the latest message.

using hidden parameters

Once the Objc_msgsend method discovers a method implementation invocation procedure, it invokes the process and passes all variables defined in the message. And it also passes two hidden variables:

    • Recipient Object
    • Method Selector

These parameters allow the implementation of each method to know the explicit information of the caller and the recipient. The reason they are "hidden" is that they are not explicitly declared in the method. They are inserted into the implementation when the code is compiled.

Although these parameters are not explicitly declared, the source code can also refer to them (as if it could refer to an instance variable of the recipient object). A method refers to the recipient object using the self variable, using a cmd variable to reference its selector. In the following example,cmd references the selector of the strange method , and the self variable points to the object that receives the strange message.

The self variable is one of the more important of the two variables. In fact, you can access the instance variables of the message receiver through it.

gets the address of a method

The only way to avoid dynamic binding is to get the address of a method and call it directly as a function. A usage scenario in this way is a special method that needs to be frequently called and you want to avoid a series of message passing every time ...

By means of the NSObject method defined in methodForSelector , you can get a pointer to the method implementation entry, and then call the procedure through this pointer. The methodForSelector returned pointer should be carefully converted to the appropriate function pointer. Both the return value and the parameter type should correspond.

The following example serfilled: The implementation of the message corresponding to the method invocation procedure:

The first two parameters of the function call are the recipient object (self) and the message selector (_cmd). These parameters are hidden in the method syntax, but must be explicitly given when the method is called through a function.

Use methodforselector: You can bypass dynamic binding to save time on message delivery. However, this savings is only possible in cases where special messages need to be frequently called multiple times, as shown in the For loop.

Note : methodForSelector It is provided by the Cocoa runtime system and is not part of the language of OC.

Dynamic loading mechanism

This chapter will introduce a method for the implementation of ze-like dynamic.

Dynamic loading mechanism

During the encoding process, you may encounter a time when dynamically providing a method implementation. For example, a property declared as @dynamic in the OC language:

Tells the compiler that the method associated with this property is dynamically provided.

You can implement resolveInstanceMethod: resolveClassMethod: a selector or class method of a specified instance dynamically by implementing and using a method.

An OC method is simply a C function--self and _cmd with at least two parameters. You can use class_addMethod methods to add a method to a class. Then, in the following way:

You can dynamically add a method (called a) to a class resolveThisMethodDynamically that uses the same way resolveInstanceMethod: as this:

Generally speaking, the message forwarding mechanism and the dynamic loading method are orthogonal. A class has the opportunity to dynamically load a method before the forwarding mechanism is involved. If respondsToSelector: or instancesRespondToSelector: is called, the dynamic loading mechanism will have the opportunity to provide the selector with an imp first. If you do resolveInstanceMethod: , but you want some selectors to actually load through the forwarding mechanism, you can choose to return these selectors to No.

Dynamic Loading

An OC application can dynamically load and link new classes and categories. The newly added code is treated as equally as the classes and categories that were originally added.

Dynamic loading can be used on many different things. For example, many of the modules in a system Setup program are loaded dynamically.

In the cocoa environment, dynamic loading is commonly applied to personalization applications. Others can load custom settings modules by writing the modules that your application loads at runtime-just like IB (Interface Builder) loads custom components and OS X system setup programs. The Loadable module expands your application. They are loaded in a way that you allow but that you do not participate in and define. You provide the framework for others to provide code.

Although there is an OC runtime function that provides a dynamically loaded OC module (objc_loadmodules, defined in objc/objc-load.h), Cocoa's NSBundle class provides a more convenient dynamically loaded interface-- An object-oriented interface that integrates with related services. Related content can be related to the relevant documentation.

OC run-time Programming Guide

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.