objective-c block vs selector. which one is better

2019-02-22 18:32发布

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?

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-02-22 18:51

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:

Blocks represent typically small, self-contained pieces of code. As such, they’re particularly useful as a means of encapsulating units of work that may be executed concurrently, or over items in a collection, or as a callback when another operation has finished.

Blocks are a useful alternative to traditional callback functions for two main reasons:

They allow you to write code at the point of invocation that is executed later in the context of the method implementation. Blocks are thus often parameters of framework methods.

They allow access to local variables. Rather than using callbacks requiring a data structure that embodies all the contextual information you need to perform an operation, you simply access local variables directly.

On this page

查看更多
劳资没心,怎么记你
3楼-- · 2019-02-22 18:58

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.

查看更多
登录 后发表回答