iOS SEL类型

234 阅读2分钟

什么是SEL类型

  • SEL类型代表着方法的签名,在类对象的方法列表中存储着该签名与方法代码的对应关系

  • 每个方法都有一个与之对应的SEL类型的对象

  • 根据一个SEL对象就可以找到方法的地址,进而调用方法

  • 首先把test这个方法名包装成sel类型的数据

  • 根据SEL数据到该类的类对象中,去找对应的方法的代码,如果找到了就执行该代码

  • 如果没有找到根据类对象上的父类的类对象指针,去父类的类对象中查找,如果找到了,则执行父类的代码

  • 如果没有找到,一直像上找,直到基类(NSObject)

  • 如果都没有找到就报错。

SEL使用

  • 配合对象/类来检查对象/类中有没有实现某一个方法
    SEL sel = @selector(setAge:);
    Person *p = [Person new];
    // [对象 respondsToSelector]用于判断是否包含某个对象方法
    // [类名 instancesRespondToSelector]用于判断是否包含某个对象方法


    // 判断p对象中有没有实现-号开头的setAge:方法
    // 如果P对象实现了setAge:方法那么就会返回YES
    // 如果P对象没有实现setAge:方法那么就会返回NO
    BOOL flag = [p respondsToSelector:sel];
    
    // 如果是通过类来调用该方法, 那么会判断该类有没有实现+号开头的方法
    flag = [Person respondsToSelector:sel1];
    
  • 配合对象/类来调用某一个SEL方法
@interface Person : NSObject
+ (void)test;

- (void)demo;

- (void)signalWithNumber:(NSString *)number;

- (void)sendMessageWithNumber:(NSString *)number andContent:(NSString *)content;

@end

@implementation Person
+ (void)test
{
    NSLog(@"test");
}

- (void)demo
{
    NSLog(@"demo");
}

- (void)signalWithNumber:(NSString *)number
{
    NSLog(@"number = %@", number);
}

- (void)sendMessageWithNumber:(NSString *)number andContent:(NSString *)content
{
    NSLog(@"number = %@, content = %@", number, content);
}

@end
    //对象方法
    SEL sel = @selector(demo);
    Person *p = [Person new];
    // 调用p对象中sel类型对应的方法
    [p performSelector:sel];
    
    //类方法
    [Person performSelector:@selector(test)];

    //带一个参数的方法
    SEL sel1 = @selector(signalWithNumber:);

    // withObject: 需要传递的参数
    // 注意: 如果通过performSelector调用有参数的方法, 那么参数必须是对象类型,
    // 也就是说方法的形参必须接受的是一个对象, 因为withObject只能传递一个对象
    [p performSelector:sel1 withObject:@"13838383438"];

    
    //带两个参数的方法
    // 注意:performSelector最多只能传递2个参数
    SEL sel3 = @selector(sendMessageWithNumber:andContent:);
    [p performSelector:sel3 withObject:@"138383438" withObject:@"abcdefg"];
  • 配合对象将SEL类型作为方法的形参
@interface Person : NSObject
// 调用传入对象的指定方法
- (void)makeObject:(id)obj andSel:(SEL)sel;
@end

@implementation Person
- (void)makeObject:(id)obj andSel:(SEL)sel
{
    [obj performSelector:sel];
}
@end

@implementation Car
- (void)run
{
    NSLog(@"run");
}
@end
    Car *c = [Car new];
    SEL sel = @selector(run);
    Person *p = [Person new];
    [p makeObject:c andSel:sel];