你想要什么在Objective-C中被称为 块语法 。虽然当然不是最好看的东西,或者最容易记住的东西,它会做你想要的。
// declares a block named 'foo' (yes, the variable name goes inside the parens) NSUInteger (^foo)(NSString *) = ^(NSString *baz) { return [baz length]; }; // now you can call foo like a function: NSUInteger result = foo(@"hello world"); // or pass it to something else: [someObject doSomethingWith:foo]; // A method that takes a block looks like this: - (void)doSomethingWith:(NSUInteger (^)(NSString *))block;
这个网站 是一个方便的“备忘单”,列出了在Objective-C中声明一个块的所有方法。你可能会经常提到它。我链接到的URL是一个更新的,工作友好的镜像。如果您考虑一下,我相信您可以猜到网站的原始网址。 ;-)
基本上每当你看到一个 ^ 在Objective-C中,您正在查看块声明。当然,除非您正在考虑XOR操作。但通常它只是一个块。
^
的 编辑: 强> 查看我链接到的网站,其中显示“作为方法调用的参数”。您需要使用该语法声明它,即
... comparison: ^BOOL(id o) { return ([o floatValue] > threshold); }];
我知道这不是世界上最直观的语法,这就是为什么该网站作为备忘单有用的原因。
此外,与您的问题无关,但Objective-C命名约定是使用小写字母启动参数标签;即 range: , options: ,和 comparison: 而不是 Range: , Option: , Comparison: 。
range:
options:
comparison:
Range:
Option:
Comparison: