What does this caret ^ syntax, with void on either side mean? [duplicate]

廉价感情. 提交于 2020-01-08 17:17:46

问题


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 parameter 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 )
{
}

回答1:


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

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.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);



回答2:


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

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



回答3:


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




回答4:


Functions can be masked as follows.

#if NS_BLOCKS_AVAILABLE
- (void)foo;
#endif


来源:https://stackoverflow.com/questions/3499186/what-does-this-caret-syntax-with-void-on-either-side-mean

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