MST
星途 面试题库

面试题:Objective-C中@selector的常见用法及原理

请阐述Objective-C中@selector的常见使用场景,比如在消息传递、代理模式等方面是如何运用的,并简要说明@selector背后的原理。
12.5万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试

@selector常见使用场景

  1. 消息传递:在Objective-C中,@selector用于指定要发送给对象的方法。例如,使用performSelector:withObject:系列方法时,通过@selector指定要执行的方法。
// 定义一个类
@interface MyClass : NSObject
- (void)printHello;
@end

@implementation MyClass
- (void)printHello {
    NSLog(@"Hello!");
}
@end

// 使用performSelector:withObject:发送消息
MyClass *obj = [[MyClass alloc] init];
[obj performSelector:@selector(printHello)];
  1. 代理模式:在代理模式中,代理对象需要知道要调用委托对象的哪个方法。@selector常用于在协议中定义方法,然后在设置代理时使用。
// 定义协议
@protocol MyProtocol <NSObject>
@optional
- (void)dataLoaded:(id)data;
@end

// 委托类
@interface DataFetcher : NSObject
@property (nonatomic, weak) id<MyProtocol> delegate;
- (void)fetchData;
@end

@implementation DataFetcher
- (void)fetchData {
    // 模拟数据获取
    id data = @"Some data";
    if ([self.delegate respondsToSelector:@selector(dataLoaded:)]) {
        [self.delegate dataLoaded:data];
    }
}
@end

// 代理类
@interface ViewController : UIViewController <MyProtocol>
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    DataFetcher *fetcher = [[DataFetcher alloc] init];
    fetcher.delegate = self;
    [fetcher fetchData];
}

- (void)dataLoaded:(id)data {
    NSLog(@"Data loaded: %@", data);
}
@end
  1. 通知中心:当注册通知时,可以使用@selector指定接收到通知后要调用的方法。
// 注册通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:@"SomeNotification" object:nil];

// 处理通知的方法
- (void)handleNotification:(NSNotification *)notification {
    // 处理通知逻辑
}

@selector背后的原理

@selector实际上是一个编译器指令,它会创建一个SEL类型的对象。SEL本质上是一个指向方法选择器的指针,它是一个在运行时用于快速查找方法实现的唯一标识符。当编译器遇到@selector时,会在编译期将方法名转换为对应的SEL。在运行时,消息发送机制会根据对象的类的方法列表,通过SEL快速定位到具体的方法实现,从而实现动态方法调用。这种机制使得Objective-C能够支持动态绑定和多态等特性。