Recently, I started to use CTMetidor to do App modularization. By the way, I will study its implementation principle

CTMetidor: NSSelectorFromString NSClassFromString SEL

Before we understand how CTMediator works, we need to understand the following concepts:

Method

Let’s look at the definition of Method

typedef struct objc_method *Method struct objc_method{ SEL method_name OBJC2_UNAVAILABLE; // Method name char *method_types OBJC2_UNAVAILABLE; // Function return value and parameter IMP method_IMP OBJC2_UNAVAILABLE; // The implementation of the method}Copy the code

We can see that the structure contains a SEL and IMP, actually equivalent to a mapping between SEL and IMP, SEL and IMP are associated, through SEL we can find the corresponding IMP, so as to call the implementation code of the method.

SEL (selector)

  • Method number, method name hash string

  • SEL is the same in any class as long as the method name is the same. All SEL in the project are stored in an NSSet (elements in the NSSet cannot be repeated), so it is only necessary to find the corresponding SEL to find the corresponding method.

Since SEL is a unique identifier for a method, what if different classes call a method with the same name?

Each method name has a unique seletor that has the same SEL but different corresponding IMP function Pointers.

How do I get SEL?

SEL s1 = @selector (test); SEL s2 = NSSelectorFromString (@"test").Copy the code

The above two methods are equivalent

IMP (implement)

  • A pointer to a function that holds the address of a method.
typedef id (*IMP)(id, SEL, ...) ;Copy the code
  • containsid(Message receiver, also known as object),SEL(Method name),parameter

XX calls XXX method, parameter XX is also determined

Execute the corresponding method:

[object test];
// @selector(test) is a C string [object selector :@selector(test)]]; Objc_msgSend (object,@selector()test))
Copy the code

conclusion

  • NSClassFromString gets a class by the name of the string, and you can get it by Target
  • NSSelectorFromString retrieves an SEL from a string (the name of an existing method)