iOS SEL的理解与使用

   有不少人,认为block的推广可取代代理设计模式,其实block并不能取代代理,代理的模式可让代码逻辑性更强,更整洁,也会有更高的可读性和可扩展性。相比之下,我以为block更多的是取代了选择器@selector。设计模式

   @selector是什么?咱们要首先明白SEL,SEL并非一种对象类型,咱们经过xCode的字体颜色就能够判断出来,它是一个关键字,就像int,long同样,它声明了一种类型:类方法指针。其实就能够理解为一个函数指针。好比,咱们生命一个叫myLog的函数指针:xcode

#import "ViewController.h"

@interface ViewController ()
{
    SEL myLog;
}
@end

声明出了这个指针,咱们该如何给它传递这个函数呢?有两种方式:函数

一、在编译时,使用@selector来取得函数字体

如今,咱们应该明白@selector是什么了,它是一个编译标示,咱们经过它来取到相应函数。spa

@interface ViewController ()
{
    SEL myLog;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    myLog = @selector(myLogL);
    //经过performSelector来执行方法
   [self performSelector:myLog];//打印 “myLog”
   
}
-(void)myLogL{
    NSLog(@"myLog");
}

二、在运行时,经过NSSelectorFromString方法来取到相应函数:设计

#import "ViewController.h"

@interface ViewController ()
{
    SEL myLog;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    myLog = NSSelectorFromString(@"myLogN");
    [self performSelector:myLog];
   
}


-(void)myLogN{
    NSLog(@"myLog");
}

这两种方式的差异在于,编译时的方法若是没有找到相应函数,xcode会报错,而运行时的方法不会。代理

至于SEL的应用,我相信最普遍的即是target——action设计模式了。咱们来简单模拟一下系统button的工做原理:指针

咱们先建立一个继承于UIButton的类:code

.h文件:orm

#import <UIKit/UIKit.h>

@interface Mybutton : UIButton
-(void)addMyTarget:(id)target action:(SEL)action;
@end

.m文件

#import "Mybutton.h"

@implementation Mybutton
{
    SEL _action;
    id _target;
}
-(void)addMyTarget:(id)target action:(SEL)action{
    _target=target;
    _action=action;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_target performSelector:_action];
}


@end

在外部:

- (void)viewDidLoad {
    [super viewDidLoad];
    Mybutton * btn = [[Mybutton alloc]initWithFrame:CGRectMake(100, 100, 60, 60)];
    btn.backgroundColor=[UIColor redColor];
    [btn addMyTarget:self action:@selector(click)];
    [self.view addSubview:btn];
}

-(void)click{
    NSLog(@"点击了btn");
}

固然,若是要调用参数,系统提供的默认参数不超过两个,若是参数不少,一种是咱们能够经过字典传参,另外一种方法比较复杂,在这里先不讨论。

 

错误之处,欢迎指正

欢迎转载,注明出处

专一技术,热爱生活,交流技术,也作朋友。

——珲少 QQ群:203317592

相关文章
相关标签/搜索