First, what is the execution time (runtime)?
- The implementation is the pure C language of Apple's development library (the implementation is often used in the development of the underlying technology)
Second, the role of implementation?
- Can get all the member variables of a class
- To get all the properties of a class
- Can get all the methods of a class
- Exchange Method implementation
- Ability to dynamically add a member variable
- Ability to add a property dynamically
- Can dynamically add a method
Third, case: Get member variable name when executing
#import <Foundation/Foundation.h>#import "CKPerson.h" #import <objc/runtime.h> int main(int argc, const Char * argv[]) {@autoreleasepool {number of//member variables unsigned intOutcount =0;//Get all the member variables //Ivars is a pointer to a member variable //ivars default to NO. 0 member variableIvar *ivars = Class_copyivarlist ([Ckpersonclass], &outcount);//Traversal of all member variables for(inti =0; i<outcount; i++) {//Remove the corresponding member variable for position I//Ivar Ivar = * (Ivars + i);Ivar Ivar = ivars[i];//Get the name of the member variableNSLog (@'%s ', Ivar_getname (Ivar)); }//Assuming that the function name includes copy\new\retain\create, the data returned by the function needs to be released manually Free(Ivars);//Ivar Ivar = *ivars;//Ivar ivar2 = * (Ivars + 1);//NSLog (@ "%s%s", Ivar_getname (Ivar), Ivar_getname (IVAR2)); //A Ivar represents a member variable //int *p; A variable that points to type int //Ivar *ivars; A variable that points to a Ivar type}return 0;}
- 2. Get the name of the uitextfiled member variable
imagemogr2/auto-orient/strip%7cimageview2/2/w/1240 "class=" Imagebubble-image "/>
// 成员变量的数量 unsignedint0; // 获得全部的成员变量 class], &outCount); // 遍历全部的成员变量 for (int0; i<outCount; i++) { // 取出i位置相应的成员变量 Ivar ivar = ivars[i]; // 获得成员变量的名字 NSLog(@"%s", ivar_getName(ivar)); } // 假设函数名中包括了copy\new\retain\create等字眼,那么这个函数返回的数据就须要手动释放 free(ivars);
Iv. iOS Bottom 1, the Runtime introduction
- Objective-c is a simple language, 95% is C. Just add some keywords and grammar to the language level. What really makes Objective-c so powerful is when it's executed. It's very small but very powerful. The core of it is message distribution.
Messages:
- Executes a method. Some languages. The compiler performs some additional optimizations and error checking because the invocation relationship is very straightforward and very obvious.
But for message distribution, it is less obvious. You do not have to know if an object can handle the message before sending it. You send the message to it, it may be processed, or it may be transferred to another object for processing. A message does not have to be a corresponding method. An object may implement a method to handle multiple messages.
- In the objective-c. The message is implemented by Objc_msgsend (), a runtime method, and a similar approach. This method requires a target. Selector, there are a few more references. Theoretically speaking. The compiler simply executes the message distribution into objc_msgsend. For example, the following two lines of code are equivalent.
[array insertObject:foo atIndex:5];objc_msgSend(array, @selector(insertObject:atIndex:), foo, 5);
Objects, Classes, metaclasses
- Most object-oriented languages have classes and objects concepts.
Objects is generated by classes.
But in the objective-c, classes itself is also objects, can also handle the message. This is also why there are class methods and instance methods. in detail. The object in Objective-c is a struct (struct), and the first member is ISA. Point to your own class. This is defined in the objc/objc.h.
typedefstruct objc_object { Class isa;} *id;
- The class of object holds a list of methods, as well as pointers to the parent class.
But classes is also objects, there will be an Isa variable, then where does it point? This leads to a third type: metaclasses. A metaclass is pointed to Class,class and is pointed to object.
It holds a list of all implemented methods. And the metaclass of the parent class. Suppose you want to get a clearer idea of how objects,classes and metaclasses together workplace to read this article.
Methods, selectors and IMPs
-
We know that execution will send a message to the object.
We also know that the class of an object holds a list of methods.
So how do these messages map to methods, and how are these methods executed?
-
The answer to the first question is very easy.
The class method list is actually a dictionary. Key is selectors,imps as value. An IMP is an implementation that points to the method in memory.
It is very important that the relationship between selector and Imp is determined at execution time, not at compile time. So we can play some tricks.
-
IMP is generally a pointer to a method, and the first parameter is self. The type is ID and the second parameter is _cmd. The type is sel, and the remainder is the method's number of parameters.
This is also where self and _cmd are defined. The following shows the method and Imp
- (id)doSomethingWithInt:(int)aInt{}id doSomethingWithInt(idselfint aInt){}
- Now that we know Objects,classes,selectors,imps and the distribution of the message, what can we do when we execute it?
What can be done at the time of execution?
Class
- The method at the beginning of class is used to modify and Introspect classes.
- Methods such as:
- To get the full contents of a class.
class_addIvar, class_addMethod, class_addProperty和class_addProtocol同意重建classes。
class_copyIvarList, class_copyMethodList, class_copyProtocolList和class_copyPropertyList
- Return a single content
class_getClassMethod, class_getClassVariable, class_getInstanceMethod, class_getInstanceVariable, class_getMethodImplementation和class_getProperty
- Some common methods of introspection
class_conformsToProtocol, class_respondsToSelector, class_getSuperclass
- Create an Object
class_createInstance来创建一个object
Ivar
- These methods allow you to get a name. Memory address and Objective-c type encoding.
Method
- These methods are mainly used for introspection. Example:
method_getName, method_getImplementation, method_getReturnType等等
ObjC
- Once you've got the object, you'll be able to do some introspection and change on it. You can get/set Ivar, use Object_copy and object_dispose to copy and free object memory. Instead of getting a class, you can use Object_setclass to change the class of an object.
Property
- Property holds a very large part of the information. In addition to getting a name, you can also use Property_getattributes to discover a lot of other information about the property. such as the return value, whether it is atomic, getter/setter name, whether it is dynamic, the Ivar name used behind it, or whether it is a weak reference.
Protocol
Sel
- Finally we have some ways to deal with selectors, such as getting a name, a selector and so on.
2. What can I do when I execute? (for example) 2.1 Classes and selectors from Strings
-
A dynamic feature of the comparative basis is the generation of classes and selectors by string. Cocoa provides nsclassfromstring and nsselectorfromstring methods that are very easy to use:
NSClassFromString(@"NSString")
-
So we got a string class. Next:
NSString *myString = [stringclass stringWithString:@"Hello World"];
-
为什么要这么做呢?Is it more convenient to use class directly? Usually it is. But in some scenarios this approach can be very useful. First, it is possible to know if there is a class,nsclassfromstring that returns nil, assuming that the class does not exist at execution time.
-
Another usage scenario is to return a different class or method based on different inputs.
For example, you are parsing some data. Each data item has a string to parse and its own type (string,number. Array). You can do this in one way, and you can use multiple methods. One of the methods is to get the type and then use if to invoke the matching method.
Another is to generate a selector based on the type, and then call it. Here are two ways to achieve this:
- (void) Parseobject: (ID) Object { for(IDDatainchObject) {if([[Data type] isequaltostring:@ "String"]) { [ SelfParsestring:[data value]]; }Else if([[Data type] isequaltostring:@ "Number"]) { [ SelfParsenumber:[data value]]; }Else if([[Data type] isequaltostring:@ "Array"]) { [ SelfParsearray:[data value]]; } }}- (void) Parseobjectdynamic: (ID) Object { for(IDDatainchObject) {[ SelfPerformselector:nsselectorfromstring([NSStringstringWithFormat:@ "parse%@:", [data type]]) withobject:[data value]]; }}- (void) ParseString: (NSString*) astring {}-(void) Parsenumber: (NSString*) Anumber {}-(void) Parsearray: (NSString*) Aarray {}
2.2 Method Swizzling
-
We talked about it before. The method consists of two parts. Selector equivalent to a method of id;imp is the implementation of the method. One of the conveniences of such separation is that the corresponding relationship between selector and IMP can be changed. For example, an IMP can have multiple selectors pointing to it.
-
The method swizzling can exchange two implementations. Maybe you'll ask, "What's the situation that would be needed?" ”。 Let's look at the two ways of extending class in Objective-c. The first is subclassing. You can rewrite a method. Calling the implementation of the parent class also means that you must use the subclass instance, but assume that you inherit a cocoa class, and cocoa returns to the original class (for example, Nsarray). In this case, you will want to add a method to Nsarray. That is, use category. 99% of the cases this is OK, but suppose you rewrite a method. There is no chance of calling the original implementation again.
-
Method swizzling can handle this problem.
You can rewrite a method without inheriting it, and you can invoke the original implementation at the same time. A common practice is to add a method to the category (and, of course, a completely new class).
It is possible to exchange implementations by method_exchangeimplementations this execution-time method.
To see a demo, this demo demonstrates how to rewrite the AddObject: method to record each newly added object.
#import <objc/runtime.h> @interface nsmutablearray (loggingaddobject)- (void) Logaddobject: (ID) Aobject;@end @implementation nsmutablearray (loggingaddobject)+ (void) Load {Method AddObject = Class_getinstancemethod ( Self,@selector(addobject:)); Method Logaddobject = Class_getinstancemethod ( Self,@selector(logaddobject:)); Method_exchangeimplementations (AddObject, logaddobject);} - (void) Logaddobject: (ID) Aobject {[ SelfLogaddobject:aobject];NSLog(@ "Added object%@ to array%@", Aobject, Self);}@end
- We put the method exchange into load, and this method is only called once. and is loaded at execution time. Imagine pointing to a temporary use and being able to put it somewhere else. Notice a very obvious recursive call to Logaddobject:. This is where the method Swizzlingeasy us, because we have exchanged the implementations of the methods, so the AddObject is actually called:
Dynamic inheritance, Exchange
-
We were able to create a new class at execution time, a feature that was not used much, but it was actually very powerful. You can create new subclasses through it and add new methods.
-
But what's the use of a subclass like this? Don't forget a key point of objective-c: There is a variable inside object called Isa that points to its class.
This variable can be changed without having to create it again. Then you can add new Ivar and methods.
Ability to change the class of an object with the following command.
object_setClass(myObject, [MySubclass class]);
-
This can be used in key Value observing. When you start observing an object. Cocoa creates the subclass of this object's class, and then points the object's Isa to the newly created subclass.
Dynamic method Processing
-
So far, we have discussed the method Exchange. and the processing of existing methods. So what happens when you send a message that an object cannot handle? Very clearly, "it breaks".
This is true in most cases. But cocoa and runtime also provide some coping methods.
-
The first is the dynamic method processing. Typically, a method is processed that executes when a matching selector is found and then executed.
Sometimes you just want to create a method at execution time, for example, some information is only available at execution time. To achieve this effect, you need to rewrite +resolveinstancemethod: and/or +resolveclassmethod:. If you do add a method, remember to return yes.
+ (BOOL)resolveInstanceMethod:(SEL)aSelector { if@selector(myDynamicMethod)) { class_addMethod(self"[email protected]:"); returnYES; } return [super resolveInstanceMethod:aSelector];}
Message forwarding
-
Suppose resolve method returns No. Proceed to the next step: message forwarding. There are two common use cases. 1) forward the message to an object that is capable of processing the message. 2) forward multiple messages to the same method.
-
Message forwarding is a two-step phase. First, the execution calls-forwardingtargetforselector: If you just want to send the message to an object, use this method because it is more efficient.
Assuming you want to change the message, use-forwardinvocation: To package the message into nsinvocation when executed. And then return it to you for processing. After processing, call Invokewithtarget:.
-
Cocoa has several places where message forwarding is used, and the basic two places are proxies (Proxies) and response chains (Responder Chain).
Nsproxy is a lightweight class that functions as a forwarding message to an object.
It is useful to assume that you want to lazily load a property of object.
The Nsundomanager is also practical. Just intercept the message and then execute it. Instead of forwarding to other places.
-
The response chain is about how cocoa handles and sends events and behaviors to the appropriate object.
For example, the copy command was executed using CMD+C. Will send-copy: to the response chain. First Responder, which is typically the current UI. If the message is not processed, it is forwarded to the next-nextresponder. Keep going until you find an object that can handle the message, or you can't find it. Error.
Use block as Method IMP
- IOS 4.3 brings a lot of new runtime methods. In addition to the enhancement of properties and protocols. Also brings a new set of methods that start with Imp. Usually an IMP is a pointer to a method implementation. The first two parameters are object (self) and selector (_cmd). IOS 4.0 and Mac OS X 10.6 brought Block,imp_implementationwithblock () to allow us to use block as IMP, and the following snippet shows how to use block to add new methods.
IMP myIMP = imp_implementationWithBlock(^(id _selfNSString *string) { NSLog(@"Hello %@"@selector"[email protected]:@");
- Can see. The objective-c surface looks quite simple, but it is very flexible and can bring a lot of possibilities. The advantage of a dynamic language is that it does a lot of clever things without expanding the language itself. For example, key Value observing. Provides an elegant API that seamlessly integrates with existing code without the need for new language-level features.
When IOS executes