What's the difference between NSInvocation and block?
Asked Answered
D

3

5

when i say block i mean:

^(int a) {return a*a;};

besides, block is only support by iOS4 and above.

What is the difference between these two?

Diluvium answered 27/2, 2012 at 10:4 Comment(0)
J
4

An NSInvocation is a message (using a selector) to an object, with optional parameters, which can be executed later (or now), and outside the current context (mind of course what you copy vs retain or reference if you move it). NSInvocation has the benefit that you can selectively copy/refer to exactly what you need.

The block is a secret local function definition, which is able to capture portions of the current thread's context, or altogether. It's also a little easier to configure than an NSInvocation because it automatically captures, copies, and retains the thread (or scope) local context. Blocks can increase your binary size slightly, similar to functions. If taken out of the local context (e.g. when you copy a block), blocks can require quite a bit more CPU time and memory - when compared to NSInvocation.

Jori answered 27/2, 2012 at 10:15 Comment(0)
G
3

NSInvocation is an object that encapsulates a message call: the target object, the selector, the arguments and the return value. A block is an object that encapsulates a section of code and some information about the state of the program leading up to that section: specifically it records the variables on the call stack up to the creation of the block.

Both of these can clearly be used as callbacks: you can use an invocation to send a message to an object, or you can execute a block's code just like a function. What's different about them is the way you'd transport state in each case. With an invocation, you either need the target object or one of the parameters to represent the context in which the message is appearing. With a block, this context is captured automatically from the state when the block was created.

Gable answered 27/2, 2012 at 10:16 Comment(2)
block is a function? or object? As @Justin says:The block is a secret local function definitionDiluvium
It's both :). A block is an anonymous function, along with a copy of the stack at the time you created the block (more or less). It's also an Objective-C object, so that you can create copies of the block and subsequently release those copies. When you execute the block, you're really just calling its function; though the runtime also sets up the block's stack before entering the function.Gable
N
0

To put it very simply, NSInvocation is less powerful than blocks. It just encapsulates a single method call on a single object, whereas blocks can wrap many lines of arbitrary code. Even your very simple squaring block is impossible to represent using an invocation without support from an existing class that would do the squaring itself.

Nard answered 27/2, 2012 at 10:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.