漫谈Objective-C :空段selector

来源:互联网 发布:英国的域名后缀 编辑:程序博客网 时间:2024/06/06 05:24

http://blog.csdn.net/yiyaaixuexi/article/details/9254557


漫谈Objective-C :空段selector



前奏


Objective-C很有个性,一个较为鲜明的特点就是方法函数是分段式的,即函数名不写在一起,而是将其拆成N段,分别对应N个参数,大大增加了代码的可读性。

  1. #define WQ_FUNC_LOG NSLog(@"%s",__FUNCTION__)  
  2.   
  3.   
  4. - (void)firstSegment:(id)firstObj secSegment:(id)secObj thirdSegment:(id)thirdObj  
  5. {  
  6.     WQ_FUNC_LOG;  
  7. }  

为了方便说明,我在该方法中打印一下自己的方法名称。发送该信号(通俗地说是调用该方法)之后
  1.  - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];         
  4.      
  5.     [self firstSegment:@"1" secSegment:@"2" thirdSegment:@"3"];  
  6. }  

我们会得到如下的log输出,可以清晰的看到selector的名字为  firstSegment:secSegment:thirdSegment: 
  1. 2013-07-05 16:34:13.977 Test[1828:c07] -[WQTestViewController firstSegment:secSegment:thirdSegment:]  


主题



OK,前奏已完,进入主题,倘若我在函数原型中删除掉第二个参数secObj,会发生什么呢?

  1. - (void)firstSegment:(id)firstObj secSegment:(id) thirdSegment:(id)thirdObj  
  2. {  
  3.     WQ_FUNC_LOG;  
  4. }  

如果使用Xcode自动补齐方法,会发现是这样调用
  1.  - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];         
  4.      
  5.     [self firstSegment:@"1" secSegment:@"2" :@"3"];  
  6. }  

运行一下会得到如下log:

  1. 2013-07-05 17:26:10.725 Test[1976:c07] -[WQTestViewController firstSegment:secSegment::]  

结论是,方法被声明成了firstSegment:secSegment:: 这个名字,那么参数呢?当然也不难猜测和验证。
  1. - (void)firstSegment:(id)firstObj secSegment:(id) thirdSegment:(id)thirdObj  
  2. {  
  3.     WQ_FUNC_LOG;  
  4.     NSLog(@"args[] = {%@ ,%@, %@};",firstObj,thirdSegment,thirdObj);  
  5. }  

当thirdSegment和thirdObj都被视为参数,我们就不得不有这样一个大胆的猜想,难道selector可以支持空段?难道selector可以没有名字?
尝试造一个没有名字的方法,准确的说法是,一个空的selector

  1. - (void) :(id)obj  
  2. {  
  3. }  
  4.   
  5. - (void)viewDidLoad  
  6. {  
  7.     [super viewDidLoad];  
  8.           
  9.     SEL sel = @selector(:);  
  10.     if ([self respondsToSelector:sel]) {  
  11.         NSLog(@"ur right");  
  12.     }  
  13. }  


编译运行,Log输出告诉我们,我们的猜想是正确的,Objective-C支持空段selector。




结论



Objective-C支持空段selector,这显然不具备良好的代码可读性,平时我们也不会这么写这么用,那为什么还要特别提出来说这件事呢?只是想给大家提个醒,有时候我们的一个粗心或者一个不小心,就有可能酿成一个需要debug好久的低水准bug,尤其是,delegate方法命名又臭又长的时候……
原创粉丝点击