iphone - 有没有办法使用 NSPredicate predicateWithFormat : 中的函数

标签 iphone core-data fetch

我有一个带有坐标(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/

相关文章:

iphone - 从 appdelegate 中的线程跨多个 View Controller 触发事件

ios - 当我只是将数据存储在内存中(而不是磁盘)时,如何有效地删除我的核心数据存储?

ios - 使用带 NSBatchDeleteRequest 的 NSFetchedResultsController

hibernate - Hibernate标准中的关联大小

reactjs - 如果状态码为400,如何获取获取响应数据

iphone - -[NSOperationQueue操作]返回一个不应该的空数组?

iphone - 在 iPhone 应用程序中使用 C++ 结构

iphone:如何进行翻页

ios - 核心数据 : Expression tree is too large

javascript - 如何测试使用 whatwg-fetch 和 mocha 的代码?