年年有"余"

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 2303|回复: 0

SEL在方法调用中的使用

[复制链接]
  • TA的每日心情
    奋斗
    2022-12-13 21:26
  • 签到天数: 371 天

    [LV.9]以坛为家II

    发表于 2014-3-18 15:11:26 | 显示全部楼层 |阅读模式
    1、取函数名的两种方式:
         __func__直接代表当前函数名
         通过方法中的SEL类型数据"_cmd"内容读取,将函数名取出;

    2、对象方法调用实际是在类中将所有方法进行SEL索引后找出相对应的方法执行,所以先将方法名进行SEL类型转换,再传给对象,一样可能实现调用对象方法的目的
         SEL s = @selector(方法名)
         [对象名 performSelector:s];

    参考代码:

    Person.h
    1. //
    2. //  Person.h
    3. //  SEL
    4. //
    5. //  Created by yusian on 14-3-18.
    6. //  Copyright (c) 2014年 小龙虾论坛. All rights reserved.
    7. //
    8. #import <Foundation/Foundation.h>
    9. @interface Person : NSObject
    10. + (void)test;
    11. - (void)test1;
    12. @end
    复制代码
    Person.m
    1. //
    2. //  Person.m
    3. //  SEL
    4. //
    5. //  Created by yusian on 14-3-18.
    6. //  Copyright (c) 2014年 小龙虾论坛. All rights reserved.
    7. //
    8. #import "Person.h"
    9. @implementation Person
    10. + (void)test
    11. {
    12.     // 通过__func__将当前函数名输出
    13.     NSLog(@"__func__ = %s", __func__);
    14.    
    15.     // 每个方法中都有一个隐含的SEL类型数据"_cmd",该数据用来表示当前方法的方法名,通过
    16.     NSString * str = NSStringFromSelector(_cmd);
    17.    
    18.     // 输出字符串中的内容,即SEL类型_cmd中储存的信息
    19.     NSLog(@"_cmd = %@", str);
    20. }
    21. - (void)test1
    22. {
    23.     NSLog(@"对象方法test1被调用...");
    24. }
    25. @end
    复制代码
    main.m
    1. //
    2. //  Person.m
    3. //  SEL
    4. //
    5. //  Created by yusian on 14-3-18.
    6. //  Copyright (c) 2014年 小龙虾论坛. All rights reserved.
    7. //
    8. #import "Person.h"
    9. @implementation Person
    10. + (void)test
    11. {
    12.     // 通过__func__将当前函数名输出
    13.     NSLog(@"__func__ = %s", __func__);
    14.    
    15.     // 每个方法中都有一个隐含的SEL类型数据"_cmd",该数据用来表示当前方法的方法名,通过
    16.     NSString * str = NSStringFromSelector(_cmd);
    17.    
    18.     // 输出字符串中的内容,即SEL类型_cmd中储存的信息
    19.     NSLog(@"_cmd = %@", str);
    20. }
    21. - (void)test1
    22. {
    23.     NSLog(@"对象方法test1被调用...");
    24. }
    25. @end
    复制代码
    输出结果:
    2014-03-18 15:10:58.372 SEL[3357:303] __func__ = +[Person test]
    2014-03-18 15:10:58.374 SEL[3357:303] _cmd = test
    2014-03-18 15:10:58.374 SEL[3357:303] 对象方法test1被调用...
    Program ended with exit code: 0

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    手机版|小黑屋|Archiver|iOS开发笔记 ( 湘ICP备14010846号 )

    GMT+8, 2024-5-5 23:04 , Processed in 0.044676 second(s), 19 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表