iOS Runtime详解(新手也看得懂)

2020-01-21 07:51:57刘景俊


@property SEL selector;

可以看到selector是SEL的一个实例。

A method selector is a C string that has been registered (or “mapped“) with the Objective-C runtime. Selectors generated by the compiler are automatically mapped by the runtime when the class is loaded.

其实selector就是个映射到方法的C字符串,你可以用 Objective-C 编译器命令@selector()或者 Runtime 系统的sel_registerName函数来获得一个 SEL 类型的方法选择器。

selector既然是一个string,我觉得应该是类似className+method的组合,命名规则有两条:

  • 同一个类,selector不能重复
  • 不同的类,selector可以重复

    这也带来了一个弊端,我们在写C代码的时候,经常会用到函数重载,就是函数名相同,参数不同,但是这在Objective-C中是行不通的,因为selector只记了method的name,没有参数,所以没法区分不同的method。

    比如:

    
    - (void)caculate(NSInteger)num;
    - (void)caculate(CGFloat)num;

    是会报错的。

    我们只能通过命名来区别:

    
    - (void)caculateWithInt(NSInteger)num;
    - (void)caculateWithFloat(CGFloat)num;