Summarize the use of runtime in IOS _ios

Source: Internet
Author: User
Tags reflection

iOS friends know or hear about runtime, which is much like the reflection mechanism of Java , but the function is much better than the reflection of Java . By Runtime we can dynamically add attributes, member variables, methods , and read and write access to a class.

Introduction of runtime

Runtime short run time. OC is the run-time mechanism , that is, some of the mechanisms at run time, the most important is the message mechanism.

For the C language, the call to a function determines which function to call at compile time .

For OC functions, which belong to the dynamic invocation process , it is not possible to determine which function is actually invoked at compile time, only when it is actually run, according to the name of the function

Find the corresponding function to invoke.

Facts have proved that:

At compile time, OC can call any function , even if the function is not implemented, as long as the declaration will not error.

In the compile phase, the C language calls an not implemented function and the error occurs.

Second, the role of runtime

1. Send Message

The essence of a method invocation is to let an object send a message.

objc_msgSend,Only objects can send messages, so start with OBJC.

Using message mechanism prerequisites, you must import#import <objc/message.h>

Message mechanism simple to use

Message mechanism principle: the object according to the method number sel to map the mapping table to find the corresponding method realization

   Create a Person object person
  *p = [[Person alloc] init];

  Call object method
  [P eat];
  SEL: Method number, according to method number can find corresponding method implementation
  [P Performselector: @selector (Eat)];

  Nature: Let objects send messages
  objc_msgsend (p, @selector (Eat));

  How to invoke a class method: two
  //one converts an essential class name to a class object by calling the class name
  [person eat];
  The second type invokes
  [[Person class] eat] through the class object;

  [Personclass performselector: @selector (Eat)];
  Call the class method with the class name, and the bottom will automatically convert the class name to class object invocation
  //Essence: Let class object Send message
  objc_msgsend ([Person class], @selector (eat));

2. Exchange method

Development of the use of the scene: The system's own method is not enough, to the system with the method to extend some functions, and maintain the original function.

mode One: inherits the system's class, overrides the method.

mode two: use runtime, Exchange method.

@implementation Viewcontroller-(void) viewdidload {[Super viewdidload];
  Do no additional setup after loading the view, typically from a nib.
  Requirements: To provide the Imagenamed method function, each load picture to determine whether the picture is loaded successfully.
  Step one: First make a classification, define a can load picture and can print method + (UIImage *) xmg_imagenamed: (NSString *) imagename;
  Step two: Exchange imagenamed and xmg_imagenamed implementation, you can call the xmg_imagenamed, indirectly invoke the xmg_imagenamed implementation.

     UIImage *image = [UIImage imagenamed:@ "123"]; Imagenamed: Implementation method: Bottom Call Ph_imagenamed Essence: Exchange Two methods of implementation imagenamed and ph_imagenamed method call imagenamed is actually called ph_imagenamed I Magenamed load the picture, do not know whether the picture is loaded successfully after the call imagenamed, you know whether the picture is loaded} @end @implementation uiimage (image)//load classification to memory when called + (V OID) load {//Exchange method implementation, methods are defined within the class//Class_getmethodimplementation: Get method Implementation//Class_getinstancemethod: Get Object///Class_g Etclassmethod: Getting class Methods//IMP: Method Implementation//Imagenamed/class: Get which class method/SEL: Get method number, according to the SEL can go to the corresponding class to find methods method Imagenamem

  Ethod = Class_getclassmethod ([UIImage class], @selector (imagenamed:)); Method Ph_imagenamemethod = Class_getclassmethod ([UIImage class], @selector (ph_imagenamed:));
The Exchange method realizes Method_exchangeimplementations (Imagenamemethod, Ph_imagenamemethod);

The system method imagenamed cannot be overridden in the classification because it overrides the functionality of the system and cannot call super in the category. Can both load picture and print + (UIImage *) ph_imagenamed: (NSString *) imagename {//load picture uiimage *image = [UIImage ph_imagenamed:image
  Name];
  2. Judgment function if (image = = nil) {NSLog (@ "loaded as null");
} return image; } @end

3. Dynamic Add method

Development Use Scenario: If a class method is very much, loading the class to memory is also more resource-intensive, you need to generate a mapping table for each method, you can use dynamic to a class, add method to solve.

Simple to use

@implementation Viewcontroller-(void) viewdidload {[Super viewdidload];

  Do no additional setup after loading the view, typically from a nib.

  Person *p = [[Person alloc] init];
  The default person, which does not implement the Eat method, can be invoked by Performselector, but an error is presented.

Add methods dynamically without error [P Performselector: @selector (Eat)]; @end @implementation person//Void (*)//default method has two implicit parameters, and the default method has two parameters, self,_cmd, implicit argument self: Method caller _cmd: Calling method's number void

Eat (ID Self,sel SEL) {NSLog (@ "%@%@", Self,nsstringfromselector (SEL));}
When an object invokes a method that is not implemented, this method is invoked and the corresponding method list is passed. Just can be used to determine whether the method that is not implemented is the method we want to add dynamically <!--dynamic Add method, first implement this resolveinstancemethod--> <!--Resolveinstancemethod call: The resolveinstancemethod--> <!--Resolveinstancemethod function is invoked when a method that does not implement is invoked: you know which methods are not implemented, thereby dynamically adding methods--> <!-- SEL: No Implementation method--> + (BOOL) Resolveinstancemethod: (SEL) sel {if (sel = = @selector (eat)) {//Dynamically add Eat method///First parameter: Give Which class adds a method//The second parameter: The method number//third argument for adding a method (function address)//Fourth parameter: type of function, (return value + parameter type) v:void @: Object->seLF: Indicates Sel->_cmd class_addmethod (self, @selector (eat), eat, "v@:");
return [Super Resolveinstancemethod:sel]; } @end

4. Add attributes to Categories

Principle: To declare an attribute to a class, the essence is to add an association to this class, not directly to add the value of the memory space to the class storage space.

@implementation Viewcontroller

-(void) viewdidload {
  [super viewdidload];
  Do no additional setup after loading the view, typically from a nib.

  Dynamically add attributes to the system NSObject class name

  nsobject *OBJC = [[NSObject alloc] init];
  Objc.name = @ "abc";
  NSLog (@ "%@", objc.name);
}
@end


//Defines the associated key
static const char *key = "name";

-(void) SetName: (NSString *) name
{
  //Add attribute, associate with object//
  to an object, add attribute
  //object: Add attribute//key to which object
  : Property name, according to key to get the associated object, void * = = ID
  //value: Associated value
  //policy: Policy

  objc_setassociatedobject (self, @ "name", Name, objc_association_retain_nonatomic);
-(NSString *) name
{return

  objc_getassociatedobject (self, @ "name");
}

The above is the use of iOS runtime summary, this article is mainly the principle and usage summary, runtime function is very powerful, but also need a lot of friends to learn and research can. I hope this article is helpful to everyone.

Related Article

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.