iOS-SEL的用法和讲解

作者: 洲洲哥 | 来源:发表于2016-12-26 10:29 被阅读202次

    本文首发地址
    1:什么是SEL:
    可理解成@selector(),方法选择器。于是乎就可说成是C中的指针函数。而在oc里不能用指针函数,所有就只能搞一个@selector这来取了。
    他的结果是SEL类型,用assgin修饰。去取方法的编号(函数地址)

    2:使用
    2.1 示例代码
    SELView.h

    /**SEL实现*/
    #import <UIKit/UIKit.h>
    
    @interface SELView : UIView
    
    /**自定义的SEL*/
    @property (nonatomic, assign) SEL  customMethod;
    /**正常调用函数*/
    -(void)printfString:(NSString *)msg;
    
    /**SEL调用*/
    -(void)testMethod;
    /**SEL调用带参数*/
    -(void)testMethod:(NSString *)msg;
    
    -(void)runMethod;
    @end
    

    SELView.m

    #import "SELView.h"
    
    @implementation SELView
    
    -(void)printfString:(NSString *)msg {
        NSLog(@"-----printfString%@",msg);
    }
    
    /**无参数函数*/
    -(void)testMethod{
        NSLog(@"-----testMethod");
    }
    /**有参数函数*/
    -(void)testMethod:(NSString *)msg {
        NSLog(@"-----(有参数函数)testMethod:%@",msg);
    }
    
    
    -(void)runMethod{
        if (_customMethod) {
            [self performSelector:_customMethod withObject:nil];
        }
    }
    

    2.2 调用详解

    //实例化对象
    SELView *views = [[SELView alloc] init];
    

    2.2.1 正常调用的方式如下

    [views printfString:@"1:自定义的打印功能"];
    

    2.2.2 传入SEL方法调用
    NOTICE:这里我们用的@selector方法一定要是当前SEL类中的函数,应为当前Class是一个isa指针,而这个@selector就是调用当前isa中方法,取其中的编号。

    /**传入的方法*/
    views.customMethod = @selector(testMethod);
    

    这里的testMethod就是当前views中的方法。否则当前对象无target,就会有错!
    2.2.3 执行Selector和传参

    /**无参数函数*/
    [views performSelector:@selector(testMethod)];
    /**有参数函数*/
    [views performSelector:@selector(testMethod:) withObject:@"传入参数"];
    

    2.2.4 SEL和NSString装换

    /**将一个字符串转换成SEL类型*/
    //SEL s1 = NSSelectorFromString(@"customClick");
    SEL s2 = @selector(customClick);
    [self performSelector:s2];
    

    NOTICE:这个时候会有一个提示performselectorm may cause a leak because its selector is unknow,在ARC模式下,运行时需要知道如何处理你正在调用的方法的返回值。这个返回值可以是任意值,如 void , int , char , NSString , id 等等。ARC通过头文件的函数定义来得到这些信息。所以平时我们用到的静态选择器就不会出现这个警告。因为在编译期间,这些信息都已经确定。
    而使用 [someController performSelector: NSSelectorFromString(@"customClick")]; 时ARC并不知道该方法的返回值是什么。最后搞的什么鬼都不认识了。如何处理 请各位看官看我的下一篇文章。如何解决。

    如有问题可添加我的QQ:1290925041
    还可添加QQ群:234812704(洲洲哥学院)
    欢迎各位一块学习,提高逼格!
    也可以添加洲洲哥的微信公众号

    更多消息

    更多信iOS开发信息 请以关注洲洲哥 的微信公众号,不定期有干货推送:

    这里写图片描述

    相关文章

      网友评论

        本文标题:iOS-SEL的用法和讲解

        本文链接:https://www.haomeiwen.com/subject/elkjvttx.html