面向对象 - SEL类型

本文介绍了SEL类型在面向对象编程中的作用,包括其作为方法签名的表示,如何检查对象或类是否实现特定方法,以及如何配合对象调用SEL方法。通过SEL,可以找到方法的地址并执行相应操作。此外,还讨论了在方法参数中使用SEL的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SEL类型概述

SEL类型代表着方法的签名,在类对象的方法列表中存储着该签名与方法代码的对应关系
每个类的方法列表都存储在类对象中
每个方法都有一个与之对应的SEL类型的对象
根据一个SEL对象就可以找到方法的地址,进而调用方法

检查对象/类中是否实现了某个方法

#import <Foundation/Foundation.h>

@interface Person : NSObject

@property int age;

+ (void)test;
@end

@implementation Person

+ (void)test{
    NSLog(@"test");
}
@end

int main(int argc, const char * argv[]) {
    
    // 查看对象中是否存在某个方法
    SEL sel1 = @selector(setAge:);
    Person *p = [[Person alloc] init];
    BOOL flag = [p respondsToSelector:sel1];
    NSLog(@"flag --> %i", flag);    // flag --> 1
    
    // 查看类中是否存在某个方法
    SEL sel2 = @selector(test);
    flag = [Person respondsToSelector:sel2];
    NSLog(@"flag --> %i", flag);    // flag --> 1
    
    return 0;
}

配合对象/类来调用某个SEL方法

使用performSelector调用类方法或对象方法时,最多传递2个参数,参数类型必须是对象类型

#import <Foundation/Foundation.h>

@interface Person : NSObject

@property int age;
@property NSString *name;

+ (void)test;

+ (void)print: (NSString *)msg;
@end

@implementation Person

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


+ (void)print:(NSString *)msg {
    NSLog(@"msg --> %@", msg);
}

@end

int main(int argc, const char * argv[]) {
    
    // 使用performSelector调用对象需要传参数的方法,参数必须是对象类型
    SEL sel1 = @selector(setName:);
    Person *p = [[Person alloc] init];
    [p performSelector:sel1 withObject:@"张三"];
    NSLog(@"name --> %@", [p name]);    // name --> 张三
    
    
    
    // 使用performSelector调用类不需要传参数的方法
    SEL sel2 = @selector(test);
    [Person performSelector:sel2];  // test
    
    // 使用performSelector调用类需要传参数的方法,参数必须是对象类型
    SEL sel3 = @selector(print:);
    [Person performSelector:sel3 withObject:@"hello"];      // msg --> hello
    
    
    return 0;
}

配合对象将SEL类型作为方法的形参

#import <Foundation/Foundation.h>

@interface Person : NSObject

- (void)makeObject:(id)obj :(SEL)sel;

@end

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

@end

@interface Car : NSObject

- (void)run;
@end

@implementation Car

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

@end

int main(int argc, const char * argv[]) {
    
    Car *c = [Car new];
    SEL sel = @selector(run);
    
    Person *p = [Person new];
    [p makeObject:c :sel];  // run
    
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值