# # One, Runtime introduction
*runtime Short run time. OC is the ' runtime mechanism ', which is the mechanism at runtime, the most important of which is the message mechanism.
* For the C language, the ' function ' call will determine which function to invoke when compiling.
* For OC functions, which is a ' dynamic call process ', at compile time it is not possible to decide which function to actually call, but only when the function is actually running, it will find the corresponding function according to its name.
* Facts show that:
* In the compile phase, 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 the ' non-implemented function ' will error.
# # # Two, runtime role
# # # #1. Send a message
* The essence of a method call is to have the object send a message.
*objc_msgsend, only objects can send messages, so start with OBJC.
* use ' message mechanism ' premise, must import #import <objc/message.h>
* Message mechanism simple to use
```
Create Person Object
Person *p = [[Person alloc] init];
Calling Object methods
[P eat];
Essence: Let the object send a message
Objc_msgsend (p, @selector (eat));
How to invoke a class method: two types of
The first is called by the class name
[Person eat];
The second is called Through the class object
[Person class] eat];
Call the class method with the class name, and the underlying will automatically convert the class name into a class object call
Essence: Let a class object send a message
Objc_msgsend ([Person class], @selector (eat));
```
* Message mechanism Principle: object based on method number SEL to map table find corresponding method implementation
*! [] (Snip20151013_4.png)
# # # #2. Method of Exchange
* Development of the use of the scene: The system comes with the method is not enough, to the system's own method to extend some functions, and maintain the original function.
* Way One: Inherit the class of the system, overriding the method.
* Mode two: Use runtime, Exchange method.
```
@implementation Viewcontroller
-(void) Viewdidload {
[Super Viewdidload];
Additional setup after loading the view, typically from a nib.
Requirements: To provide functionality to the Imagenamed method, each time the picture is loaded to determine whether the tablet is loaded successfully.
Step one: First make a classification, define a can load the picture and can print method + (Instancetype) Imagewithname: (NSString *) name;
Step two: Exchange imagenamed and Imagewithname implementation, you can call Imagewithname, indirectly invoke the implementation of Imagewithname.
UIImage *image = [UIImage imagenamed:@ "123"];
}
@end
@implementation UIImage (Image)
Called when the class is loaded into memory
+ (void) load
{
Exchange method
Get Imagewithname Method Address
Method imagewithname = Class_getclassmethod (self, @selector (imagewithname:));
Get Imagewithname Method Address
Method imageName = Class_getclassmethod (self, @selector (imagenamed:));
Interchange method address, equivalent to interchange implementation mode
Method_exchangeimplementations (Imagewithname, imageName);
}
The system method imagenamed cannot be overridden in the taxonomy because the system's functionality is overwritten and the super is not called in the classification.
can load pictures and print
+ (Instancetype) Imagewithname: (NSString *) name
{
This calls Imagewithname, which is equivalent to calling ImageName
UIImage *image = [self imagewithname:name];
if (image = = nil) {
NSLog (@ "Load empty picture");
}
return image;
}
@end
```
* Exchange principle:
* Before Exchange:
! [] (Snip20151013_2.png)
* After Exchange:
! [] (Snip20151013_3.png)
# # # #3. Adding methods dynamically
* Development Use Scenario: If a class method is very many, load the class to memory is also more resource-intensive, you need to generate a mapping table for each method, you can use the dynamic to a class, add methods to solve.
* Classic Interview questions: There is no use of performselector, in fact, I would like to ask you have not dynamically added methods.
* Easy to use
```
@implementation Viewcontroller
-(void) Viewdidload {
[Super Viewdidload];
Additional setup after loading the view, typically from a nib.
Person *p = [[Person alloc] init];
The default person, does not implement the Eat method, can be called through Performselector, but will error.
Dynamic Add method will not error
[P Performselector: @selector (Eat)];
}
@end
@implementation person
void (*) ()
The default method has two implicit arguments,
void Eat (ID self,sel SEL)
{
NSLog (@ "%@%@", Self,nsstringfromselector (SEL));
}
When an object calls a method that is not implemented, the method is called to process 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
+ (BOOL) Resolveinstancemethod: (SEL) SEL
{
if (sel = = @selector (eat)) {
Adding Eat methods dynamically
First argument: which class to add a method to
Second parameter: Method number for adding a method
Third parameter: Add a function implementation of a method (function address)
The fourth parameter: the type of the function, (return value + parameter type) v:void @: Object->self: Represents Sel->_cmd
Class_addmethod (self, @selector (eat), eat, "[email protected]:");
}
return [Super Resolveinstancemethod:sel];
}
@end
```
# # # #4. Adding attributes to a category
* Principle: To declare a property to a class, the essence is to add an association to the class, not directly add the value of the memory space to the class storage space.
```
@implementation Viewcontroller
-(void) Viewdidload {
[Super Viewdidload];
Additional setup after loading the view, typically from a nib.
Adding properties to the System NSObject class dynamically name
NSObject *OBJC = [[NSObject alloc] init];
Objc.name = @ "Small size elder brother";
NSLog (@ "%@", objc.name);
}
@end
Define the associated key
static const char *key = "name";
@implementation NSObject (property)
-(NSString *) name
{
Gets the associated value, based on the associated key.
Return Objc_getassociatedobject (self, key);
}
-(void) SetName: (NSString *) name
{
First argument: Which object to add the association to
Second parameter: The associated key, which is obtained by this key
Third parameter: The associated value
Fourth parameter: Associated policy
Objc_setassociatedobject (self, key, name, objc_association_retain_nonatomic);
}
@end
```
# # # #5. Dictionary to model
* Design Model: The first step of a dictionary-to-model
* Model properties, usually corresponding to key one by one in the dictionary
* Problem: One of the generation model properties, very slow?
* Requirements: Can be automatically based on a dictionary to generate the corresponding properties.
* Workaround: Provide a classification that generates a corresponding property string specifically based on the dictionary.
```
@implementation NSObject (Log)
Automatically print property strings
+ (void) Resolvedict: (Nsdictionary *) dict{
Stitching Property String Code
nsmutablestring *STRM = [nsmutablestring string];
1. Iterate through the dictionary and remove all keys from the dictionary to generate the corresponding property code
[Dict enumeratekeysandobjectsusingblock:^ (ID _nonnull key, id _nonnull obj, BOOL * _nonnull stop) {
Types often change, drawn out
NSString *type;
if ([obj iskindofclass:nsclassfromstring (@ "__nscfstring")]) {
Type = @ "NSString";
}else if ([obj iskindofclass:nsclassfromstring (@ "__nscfarray")]) {
Type = @ "Nsarray";
}else if ([obj iskindofclass:nsclassfromstring (@ "__nscfnumber")]) {
Type = @ "int";
}else if ([obj iskindofclass:nsclassfromstring (@ "__nscfdictionary")]) {
Type = @ "Nsdictionary";
}
Property string
NSString *str;
if ([Type containsstring:@ "NS"]) {
str = [NSString stringwithformat:@ "@property (nonatomic, strong)%@ *%@;", Type,key];
}else{
str = [NSString stringwithformat:@ "@property (nonatomic, assign)%@%@;", Type,key];
}
For each property string that is generated, the line wraps automatically.
[StrM appendformat:@ "\n%@\n", str];
}];
It would be nice to print out the stitched strings.
NSLog (@ "%@", StrM);
}
@end
```
* Dictionary to model one way: KVC
```
@implementation Status
+ (Instancetype) statuswithdict: (Nsdictionary *) dict
{
Status *status = [[Self alloc] init];
[Status Setvaluesforkeyswithdictionary:dict];
return status;
}
@end
```
*KVC dictionary to model cons: You must ensure that the properties in the model correspond to key one by one in the dictionary.
* If not consistent, it will be called ' [<status 0x7fa74b545d60> Setvalue:forundefinedkey:] '
The "key" cannot be found wrong.
* Analysis: The property in the model and the key of the dictionary do not correspond, the system will call ' Setvalue:forundefinedkey: ' ERROR.
* FIX: Rewrite the object's ' Setvalue:forundefinedkey: ' To override the System method,
You can continue to use KVC, the dictionary to the model.
```
-(void) SetValue: (ID) value Forundefinedkey: (NSString *) key
{
}
```
* Dictionary to model mode two: Runtime
* Idea: Use the runtime, traverse all the properties of the model, according to the model's property name, go to the dictionary to find key, take out the corresponding value, to the model's property assignment value.
* Step: Provide a nsobject classification, a special dictionary to the model, all models can be transferred through this classification.
```
@implementation Viewcontroller
-(void) Viewdidload {
[Super Viewdidload];
Additional setup after loading the view, typically from a nib.
Parsing plist files
NSString *filepath = [[NSBundle mainbundle] pathforresource:@ "status.plist" oftype:nil];
Nsdictionary *statusdict = [Nsdictionary Dictionarywithcontentsoffile:filepath];
Get dictionary Array
Nsarray *dictarr = statusdict[@ "statuses"];
Automatically generate a property string for a model
[NSObject resolvedict:dictarr[0][@ "user"];
_statuses = [Nsmutablearray array];
Iterating through a dictionary array
For (Nsdictionary *dict in Dictarr) {
Status *status = [status Modelwithdict:dict];
[_statuses Addobject:status];
}
Test data
NSLog (@ "%@%@", _statuses,[_statuses[0] user]);
}
@end
@implementation NSObject (Model)
+ (Instancetype) modelwithdict: (nsdictionary *) dict
{
//idea: Traverse all properties in Model-"Use runtime
//0. Create the corresponding object
ID OBJC = [[Self alloc] init];
//1. Assigning values to member properties in an object using runtime
//class_copyivarlist: Get all member properties in a class
//Ivar: Meaning of member properties
// The first parameter: Indicates which class is getting the member property
//second parameter: Indicates how many member properties of this class, passing in an int variable address, will automatically assign a value to this variable
//return value Ivar *: Refers to a Ivar array, which will put all member properties in an array, The returned array is fully accessible.
/* Similar to the following syntax
Ivar Ivar;
Ivar ivar1;
Ivar ivar2;
//define an array of Ivar a
Ivar a[] = {IVAR,IVAR1,IVAR2};
//With a Ivar * pointer to the first element of the array
Ivar *ivarlist = A;
//access the first element of the array according to the pointer
Ivarlist[0];
*/
unsigned int count;
//Gets all member properties in the class
Ivar *ivarlist = Class_copyivarlist (self, &count);
for (int i = 0; i < count; i++) {
//According to the corner label, remove the corresponding member property from the array
Ivar Ivar = ivarlist[i];
//Get member property name
NSString *name = [NSString stringwithutf8string:ivar_getname (Ivar)];
//Process member property name, key in dictionary
//intercept
NSString *key = [name Substringfromindex:1] from the first corner of the label;
Find the corresponding value in the dictionary according to the member property name
ID value = Dict[key];
Secondary conversions: If there are dictionaries in the dictionary, you also need to convert the corresponding dictionary into a model
Determine if value is a dictionary
if ([Value Iskindofclass:[nsdictionary class]]) {
Dictionary Turn model
Gets the class object of the model, calling Modelwithdict
The class name of the model is known, which is the type of the member property
Get member Property type
NSString *type = [NSString stringwithutf8string:ivar_gettypeencoding (Ivar)];
Generated is this @ "@\" user\ "type-" @ "User" in OC string \ "-", \ is escaped meaning, does not occupy characters
Clipping type string
Nsrange range = [type rangeofstring:@ "\"];
Type = [Type SubstringFromIndex:range.location + range.length];
Range = [Type rangeofstring:@ "\"];
Clip to which corner label, excluding current corner label
Type = [Type substringToIndex:range.location];
Generating class objects based on string class names
Class Modelclass = nsclassfromstring (type);
if (Modelclass) {//There is a corresponding model to go
Turn a dictionary into a model
Value = [Modelclass modelwithdict:value];
}
}
Level Three conversion: Nsarray is also a dictionary that converts the dictionary in an array into a model.
Determines whether the value is an array
if ([Value Iskindofclass:[nsarray class]]) {
Determine if the corresponding class has a protocol that implements a dictionary array to model array
if ([Self respondstoselector: @selector (arraycontainmodelclass)]) {
A method that can invoke any object by converting it to an ID type
ID idself = self;
Gets the model corresponding to the dictionary in the array
NSString *type = [Idself Arraycontainmodelclass][key];
Build model
Class Classmodel = nsclassfromstring (type);
Nsmutablearray *ARRM = [Nsmutablearray array];
Iterate through the dictionary array to generate the model array
For (nsdictionary *dict in value) {
Dictionary Turn model
ID model = [classmodel modelwithdict:dict];
[Arrm Addobject:model];
}
Assigning the model array to value
value = ARRM;
}
}
if (value) {//has a value, you need to assign a value to the property of the model
Assigning values to attributes in a model using KVC
[OBJC Setvalue:value Forkey:key];
}
}
return OBJC;
}
@end
```
Runtime is used in iOS in detail