NSPredicateEditorRowTemplate

NSPredicateEditorRowTemplate

我正在尝试为我的Core Data实体生成谓词编辑器模板。在我的代码中,我有以下内容:

 NSEntityDescription *descrip = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:managedObjectContext];
   NSArray *templates = [NSPredicateEditorRowTemplate templatesWithAttributeKeyPaths:[NSArray arrayWithObjects:@"name", @"age", nil] inEntityDescription:descrip];

   [ibPredicateEditor setRowTemplates: templates];

   NSPredicate *p = [NSPredicate predicateWithFormat:@"name like 'John'"];

   [ibPredicateEditor setObjectValue:p];


打印出模板数组的内容可以得到以下信息:


  CFArray 0x1002d7400 [0x7fff70ff5f20]
  {type =不变,count = 2,values =
  (
                 0:NSPredicateEditorRowTemplate
  0x10025c090:[名称] [99、4、5、8、9]
  NSStringAttributeType
                 1:NSPredicateEditorRowTemplate
  0x1002d2dc0:[年龄] [4、5、0、2、1、3]
  NSInteger16AttributeType
         )}


执行此代码后,我将在控制台上看到以下内容:

Warning - unable to find template matching predicate name LIKE "John"


这样做的界面看起来非常简单,因此我似乎无法弄清楚自己在做什么错。任何帮助将不胜感激!

编辑

我最初的问题是我的模板不支持LIKE运算符。但是,我对将复合谓词传递到编辑器时为什么会收到类似警告感到困惑。

NSPredicate *p = [NSPredicate predicateWithFormat:@"name CONTAINS 'John'"];
NSPredicate *p2 = [NSPredicate predicateWithFormat:@"name CONTAINS 'Jo'"];
NSPredicate *final = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:p, p2, nil]];
[ibPredicateEditor setObjectValue: final];


要么

NSPredicate *final = [NSCompoundPredicate orPredicateWithSubpredicates:[NSArray arrayWithObjects:p, p2, nil]];
[ibPredicateEditor setObjectValue: final];


两者都产生与我最初的问题类似的警告。但是,我感到奇怪的是,我可以使用单个谓词并构建复合词和谓词,但是无法将预构建的复合词和谓词传递给编辑器。

最佳答案

NSPredicateEditorRowTemplateNSString密钥路径提供的默认模板不支持与LIKE运算符的比较。

在生成的模板中,有一个它支持的运算符列表:

NSPredicateEditorRowTemplate 0x10025c090: [name] [99, 4, 5, 8, 9] NSStringAttributeType


[99, 4, 5, 8, 9]表示名称NSString属性支持:

4 –等于
5 –不等于
8 –始于
9 –结尾为
99 –包含

(位于NSComparisonPredicate.h中)

CONTAINS类似于没有%和_替代的LIKE。如果您需要始终可以初始化自己的模板数组。

语法有点冗长。

NSExpression *nameExpression = [NSExpression expressionForKeyPath:@"name"];
NSArray *operators = [NSArray arrayWithObjects:
      [NSNumber numberWithInt: NSEqualToPredicateOperatorType],
      [NSNumber numberWithInt:NSNotEqualToPredicateOperatorType],
      [NSNumber numberWithInt:NSLikePredicateOperatorType],
      [NSNumber numberWithInt:NSBeginsWithPredicateOperatorType],
      [NSNumber numberWithInt:NSEndsWithPredicateOperatorType],
      [NSNumber numberWithInt:NSContainsPredicateOperatorType],
      nil];

NSUInteger options = (NSCaseInsensitivePredicateOption |
                      NSDiacriticInsensitivePredicateOption);

NSPredicateEditorRowTemplate *template = [[NSPredicateEditorRowTemplate alloc]
      initWithLeftExpressions:[NSArray arrayWithObject:nameExpression]
      rightExpressionAttributeType:NSStringAttributeType
      modifier:NSDirectPredicateModifier
      operators:operators
      options:options];

09-25 19:53