Objective-C 块与选择器。哪一个更好?
例如,在 Objective-C 中,当您实现要执行重复操作的方法时,您需要在该语言为您提供的几个选项之间进行选择:
@interface FancyMutableCollection : NSObject { }
-(void)sortUsingSelector:(SEL)comparator;
// or ...
-(void)sortUsingComparator:(NSComparator)cmptr;
@end
我想知道哪个更好 ?
Objective-c 提供了许多选项:选择器、块、函数指针、符合协议的类实例等。
有时选择很明确,因为只有一种方法适合您的需求,但其余的呢?我不认为这只是时尚问题。
是否有任何规则可以知道何时使用选择器以及何时使用块?
In objective-c when you are implementing a method that is going to perform a repetitive operations, for example, you need to choice in between the several options that the language brings you:
@interface FancyMutableCollection : NSObject { }
-(void)sortUsingSelector:(SEL)comparator;
// or ...
-(void)sortUsingComparator:(NSComparator)cmptr;
@end
I was wondering which one is better?
Objective-c provides many options: selectors, blocks, pointers to functions, instances of a class that conforms a protocol, etc.
Some times the choice is clear, because only one method suits your needs, but what about the rest? I don't expect this to be just a matter of fashion.
Are there any rules to know when to use selectors and when to use blocks?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我能想到的主要区别是,对于块,它们的行为就像闭包,因此它们捕获它们周围范围内的所有变量。当您已经拥有变量并且不想创建实例变量只是为了临时保存该变量以便操作选择器可以在运行时访问它时,这非常有用。
与集合相关,如果系统中有多个核心,则块具有并发运行的附加能力。目前 iPhone 中没有,但 iPad 2 中确实有,并且未来的 iPhone 型号很可能将拥有多个核心。在这种情况下,使用块将允许您的应用程序将来自动扩展。
在某些情况下,块也更容易阅读,因为回调代码就位于回调代码的旁边。当然情况并非总是如此,但有时它确实会使代码更易于阅读。
很抱歉请您参阅文档,但要更全面地了解块的优缺点,请查看 此页面。
正如苹果公司所说:
关于 此页面
The main difference I can think of is that with blocks, they act like closures so they capture all of the variables in the scope around them. This is good for when you already have the variables there and don't want to create an instance variable just to hold that variable temporarily so that the action selector can access it when it is run.
With relation to collections, blocks have the added ability to be run concurrently if there are multiple cores in the system. Currently in the iPhone there isn't, but the iPad 2 does have it and it is probable that future iPhone models will have multiple cores. Using blocks, in this case, would allow your app to scale automatically in the future.
In some cases, blocks are just easier to read as well because the callback code is right next to the code that's calling it back. This is not always the case of course, but when sometimes it does simply make the code easier to read.
Sorry to refer you to the documentation, but for a more comprehensive overview of the pros/cons of blocks, take a look at this page.
As Apple puts it:
On this page
更好的方法是在当前情况下效果更好的方法。如果您的对象都实现了支持您想要的排序的比较选择器,请使用它。如果没有,块可能会更容易。
The one that's better is whichever one works better in the situation at hand. If your objects all implement a comparison selector that supports the ordering you want, use that. If not, a block will probably be easier.