我有一个带有坐标(x,y,z)的实体的商店。 我想通过使用像 @"sqrt(xx + yy + z*z) < distance"这样的谓词来获取它们。
有什么办法可以做到这一点吗?
我尝试使用 predicateWithFormat 来做到这一点:
我什至写了很多看起来像这样的代码
NSExpression * dxExpression = [NSExpression expressionForFunction:@"from:subtract:"
arguments:[NSArray arrayWithObjects:
[NSExpression expressionForConstantValue: [NSNumber numberWithFloat:currX]],
[NSExpression expressionForKeyPath:@"self.xCoord"], nil]
];
NSExpression * dxSqrExpression = [NSExpression expressionForFunction:@"multiply:by:"
arguments:[NSArray arrayWithObjects:dxExpression, dxExpression, nil]
];
但它仅适用于非分层表达式。即,所以 dxExpression 工作正常,但是当我尝试使用 dxSqrExpression 时,出现错误
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Unsupported function expression (-140.857 - #self.xCoord) * (-140.857 - #self.xCoord)'
我已经尝试过没有 self,但这也不起作用。
任何帮助将不胜感激,谢谢。
最佳答案
我认为您尝试做的事情是不可能的,但是您可以实现通用映射函数并重写您的 @"sqrt(x*x + y*y + z*z) < distance"
谓词作为返回 BOOL
的函数您将作为选择器传入:
@implementation NSArray(Filtering)
- (NSArray*)arrayByMappingArrayUsingSelector:(SEL)selector, ... {
NSInvocation* invocation;
va_list arguments;
if (selector && [self lastObject]) {
va_start(arguments, selector);
invocation = [NSInvocation invocationUsingSelector:selector onTarget:[self lastObject] argumentList:arguments];
va_end(arguments);
}
NSMutableArray *filteredArray = [NSMutableArray array];
BOOL returnValue;
for(id object in self) {
[invocation invokeWithTarget:object];
[invocation getReturnValue:&returnValue];
if(ret) [filteredArray addObject:object];
}
return filteredArray;
}
@end
关于iphone - 有没有办法使用 NSPredicate predicateWithFormat : 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1131180/