我需要将if语句传递给方法。在JavaScript中,您可以将功能分配给变量。然后,该变量可以传递给函数并执行。这是否存在于Objective-C?
中这是我想实现的模式:
-(void)singleComparisonWith:(NSArray *)data
IndexBegin:(NSUInteger)indexBegin
IndexEnd:(NSUInteger)indexEnd
Threshold:(float)threshold {
NSIndexSet *set1 = [self searchWithData:data
Range:[self makeInspectionWithRange:indexBegin
End:indexEnd]
Option:NSEnumerationConcurrent
Comparison:XXXXXXXXX];
// XXXXXXXXX is an IF statement that looks for value at an index above threshold
}
-(void)rangeComparisonWith:(NSArray *)data
IndexBegin:(NSUInteger)indexBegin
IndexEnd:(NSUInteger)indexEnd
ThresholdLow:(float)thresholdLow
ThresholdHigh:(float)thresholdHigh {
NSIndexSet *candidates = [self searchWithData:data
Range:[self makeInspectionWithRange:indexBegin
End:indexEnd]
Option:NSEnumerationReverse
Comparison:YYYYYYYYY];
// YYYYYYYYY is an IF statement that looks for value at an index above thresholdLow and above thresholdHigh
}
-(NSIndexSet *)searchWithData:data
Range:(NSIndexSet *)range
Option:(NSEnumerationOptions)option
Comparison:(id)comparison {
return [data indexesOfObjectsAtIndexes:range
options:option
passingTest:^(id obj, NSUInteger idx, BOOL *stop){
// Comparison is used here. Returns YES if conditions(s) are met.
}
];
}
编辑:
这是@charles srstka的解决方案。
NSIndexSet *set1 = [self searchWithData:data
Range:[self makeInspectionWithRange:indexBegin
End:indexEnd]
Option:NSEnumerationConcurrent
Comparison:BOOL^(id o) {
return ([o floatValue] > threshold);
}
];
-(NSIndexSet *)searchWithData:data
Range:(NSIndexSet *)range
Option:(NSEnumerationOptions)option
Comparison:(BOOL(^)(id o))comparison {
return [data indexesOfObjectsAtIndexes:range
options:option
passingTest:^(id obj, NSUInteger idx, BOOL *stop){
return comparison(obj);
}
];
该细分市场中没有错误。
谢谢您的帮助。
您想要的内容称为 block语法。虽然当然不是最好的事情,也不是最简单的事情,但它会做您想要的。
// 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是一个更新的,友好的镜子。我敢肯定,如果考虑到该网站的原始URL。; - )
基本上,每当您在Objective-C中看到^
时,您都在查看块声明。当然,除非您正在查看XOR操作。但通常是一个街区。
编辑:查看我链接到的网站,其中说"作为方法调用的参数"。您需要使用该语法来声明它,即
... comparison: ^BOOL(id o) {
return ([o floatValue] > threshold);
}];
我知道这不是世界上最直观的语法,这就是为什么该网站可用作备忘单。
此外,与您的问题无关,但是Objective-C命名惯例是用低写字母启动论证标签;即range:
,options:
和comparison:
而不是Range:
,Option:
,Comparison:
。