漫谈Objective-C :空段selector
来源:互联网 发布:英国的域名后缀 编辑:程序博客网 时间:2024/06/06 05:24
http://blog.csdn.net/yiyaaixuexi/article/details/9254557
漫谈Objective-C :空段selector
前奏
Objective-C很有个性,一个较为鲜明的特点就是方法函数是分段式的,即函数名不写在一起,而是将其拆成N段,分别对应N个参数,大大增加了代码的可读性。
- #define WQ_FUNC_LOG NSLog(@"%s",__FUNCTION__)
- - (void)firstSegment:(id)firstObj secSegment:(id)secObj thirdSegment:(id)thirdObj
- {
- WQ_FUNC_LOG;
- }
为了方便说明,我在该方法中打印一下自己的方法名称。发送该信号(通俗地说是调用该方法)之后
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- [self firstSegment:@"1" secSegment:@"2" thirdSegment:@"3"];
- }
我们会得到如下的log输出,可以清晰的看到selector的名字为 firstSegment:secSegment:thirdSegment:
- 2013-07-05 16:34:13.977 Test[1828:c07] -[WQTestViewController firstSegment:secSegment:thirdSegment:]
主题
OK,前奏已完,进入主题,倘若我在函数原型中删除掉第二个参数secObj,会发生什么呢?
- - (void)firstSegment:(id)firstObj secSegment:(id) thirdSegment:(id)thirdObj
- {
- WQ_FUNC_LOG;
- }
如果使用Xcode自动补齐方法,会发现是这样调用
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- [self firstSegment:@"1" secSegment:@"2" :@"3"];
- }
运行一下会得到如下log:
- 2013-07-05 17:26:10.725 Test[1976:c07] -[WQTestViewController firstSegment:secSegment::]
结论是,方法被声明成了firstSegment:secSegment:: 这个名字,那么参数呢?当然也不难猜测和验证。
- - (void)firstSegment:(id)firstObj secSegment:(id) thirdSegment:(id)thirdObj
- {
- WQ_FUNC_LOG;
- NSLog(@"args[] = {%@ ,%@, %@};",firstObj,thirdSegment,thirdObj);
- }
当thirdSegment和thirdObj都被视为参数,我们就不得不有这样一个大胆的猜想,难道selector可以支持空段?难道selector可以没有名字?
尝试造一个没有名字的方法,准确的说法是,一个空的selector
- - (void) :(id)obj
- {
- }
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- SEL sel = @selector(:);
- if ([self respondsToSelector:sel]) {
- NSLog(@"ur right");
- }
- }
编译运行,Log输出告诉我们,我们的猜想是正确的,Objective-C支持空段selector。
结论
Objective-C支持空段selector,这显然不具备良好的代码可读性,平时我们也不会这么写这么用,那为什么还要特别提出来说这件事呢?只是想给大家提个醒,有时候我们的一个粗心或者一个不小心,就有可能酿成一个需要debug好久的低水准bug,尤其是,delegate方法命名又臭又长的时候……
- 漫谈Objective-C :空段selector
- 漫谈Objective-C :空段selector
- 漫谈Objective-C :空段selector
- 挺好的 保存一下,有空看 《漫谈Objective-C :空段selector》
- Objective-C Class Selector
- Objective-C选择器 Selector
- selector in Objective-C
- Objective-C选择器 Selector
- Objective-C选择器 Selector
- Objective-c selector学习
- Objective-C中的@Selector
- Objective-C选择器 Selector
- [Objective-C] selector 简介
- Objective-C @selector
- Objective-c selector学习
- Object-C 空@selector
- iOS: Objective C "Selector" 用法
- Objective-c selector/SEL 说明
- YUV & RGB
- Python100例——第四章----素数的家族
- ucGUI 中 加入汉字库和图片的方法
- WinRAR4.2破解注册方法
- 正则表达式 匹配中文,英文字母和数字及_的写法!同时控制长度
- 漫谈Objective-C :空段selector
- 黑马程序员--Window对象的属性1
- MyEclipse8.6+Flash Builder 4.0 plug-in创建Flex-J2EE程序
- Python100例——第五章----不定方程的解
- 禁用掉KDTable向下和回车新增行事件
- Android详细的对话框AlertDialog.Builder使用方法
- Servlet API
- 如何回滚请求<复制系统初始的数据>所处理的数据
- mysql 慢查询日志(slow_query_log_file)切换