views:

331

answers:

4

In iPhone SDK 4.0 UIApplication has a new method, setKeepAliveTimeout that requires a second parameter of type 'void(^)(void)'.

-(BOOL)setKeepAliveTimeout:(NSTimeInterval)timeout handler:(void(^)(void))keepAliveHandler

What exactly does the syntax of the second param mean, and how would I declare a function/handler that I can pass into it?

FWIW the following is not what it's looking for...

void SomeHandler( void )
{
}
+6  A: 

It is a "block", a new feature Apple added to C in Snow Leopard. Lots more info available at:

http://developer.apple.com/mac/articles/cocoa/introblocksgcd.html

Block Objects

Block objects (informally, “blocks”) are an extension to C, as well as Objective-C and C++, that make it easy for programmers to define self-contained units of work. Blocks are similar to — but far more powerful than — traditional function pointers. The key differences are:

Blocks can be defined inline, as “anonymous functions.” Blocks capture read-only copies of local variables, similar to “closures” in other languages This is kind of functionality is common in dynamically-typed interpreted languages, but has never before been widely available to C programmers. Apple has published both the Blocks Languages Specification and our implementation as open source under the MIT license, added blocks support to GCC 4.2 and clang, and has submitted it for consideration as part of the next version of the C programming language.

Syntax

A block variable looks like a function pointer, except with a caret (‘^’) instead of an asterisk (‘*’).

void (^my_block)(void);
Shaggy Frog
A: 

It means it take a block (of code, aka closure) see http://developer.apple.com/mac/articles/cocoa/introblocksgcd.html These are new to objective-c for OSX 10.6 and iOS 4

superfell
+2  A: 

And the code for that particular function would look something like:

[[UIApplication sharedApplication] setKeepAliveTimeout:5.0 handler:^{
    NSLog( @"This is my timeout handler" );
}];
zpasternack
A: 

Functions can be masked as follows.

#if NS_BLOCKS_AVAILABLE
- (void)foo;
#endif
JJD