Objective-C: Why check nil before respondsToSelector:?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-21 06:47:37

问题


I've seen code like:

if (delegate != nil && [delegate respondsToSelector:@selector(doSomething)]) ...

But, sending a message to nil just returns nil (which evaluates to NO), so why not just do:

if ([delegate respondsToSelector:@selector(doSomething)]) ...

Is the former faster if delegate == nil? Either way, I prefer the latter cause it's less code.

And, less is better than more. Every Unix pro knows that.


回答1:


objc_msgSend, the function used to send dynamic messages in Objective-C immediately checks the first argument (the message receiver) and returns if it == nil. Therefore, the only overhead of nil messaging is a dynamically-linked library function call, which is slightly more costly than an "intra-binary" function call. Overall, is one approach more efficient than the other? Compound conditional statements usually require additional branching, so the answer is indeterminable without looking at the code the compiler generates, but more importantly profiling the running program. Premature optimization is a Bad Thing™, but I congratulate you for actually considering efficiency and questioning "idioms" such as this.




回答2:


You are correct. This is technically unnecessary overhead in Obj-C as any message sent to nil will return nil automatically. However, if you ignore the call to respondsToSelector: by first checking if it's nil, then you will skip the overhead of the respondsToSelector: call. So it would be faster, but by how much, I'm not sure.




回答3:


There's a syntactical issue here- if you're sending -respondsToSelector to a nil object, it will always return nil. This is why you would do such a thing.



来源:https://stackoverflow.com/questions/6479267/objective-c-why-check-nil-before-respondstoselector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!