面试题答案
一键面试@selector常见使用场景
- 消息传递:在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)];
- 代理模式:在代理模式中,代理对象需要知道要调用委托对象的哪个方法。
@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
- 通知中心:当注册通知时,可以使用
@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能够支持动态绑定和多态等特性。