【问题标题】:NSPredicate for an NSManagedObject's string attribute's lengthNSManagedObject 的字符串属性长度的 NSPredicate
【发布时间】:2011-04-08 08:39:35
【问题描述】:

有人可以帮我定义一个谓词,它只返回 NSManagedObject 的谁的“字母”属性长度在一定范围内吗?

这是我一直在尝试的示例,我感觉它是 letters.length 表示法,我也尝试了 kvc letters.@length 没有成功..我做错了什么?

NSManagedObjectContext *context = ...;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Word" inManagedObjectContext:context];
[fetchRequest setEntity:entity];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"letters" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"letters.length BETWEEN %@", [NSArray arrayWithObjects: [NSNumber numberWithInt:5], [NSNumber numberWithInt:20], nil]];
[fetchRequest setPredicate:predicate];

NSUInteger limit = 20;
[fetchRequest setFetchLimit:limit];

NSError *error = nil;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];

【问题讨论】:

    标签: core-data nsstring nspredicate nsmanagedobject


    【解决方案1】:

    我有一些坏消息。你不能这样做。 NSPredicate 中没有字符串的长度属性(我已经能够找到)。

    我建议您在托管对象中添加一个存储字符串长度的属性,该属性在您设置 letters 属性时设置。然后,您可以对该属性进行查询并返回您想要的值。

    【讨论】:

      【解决方案2】:

      如果有人正在寻找一种使用 NSPredicate 测试字符串是否有长度的方法, possible

      【讨论】:

      • 请注意,您链接的解决方案不适用于核心数据,正如 SO 所要求的那样。
      【解决方案3】:

      不确定此代码 sn-p 的性能如何,但这是我对您问题的回答:

      NSString *attributeName = @"letters";
      NSString *attributeValue = [NSString stringWithFormat:@"'.{%d,%d}'", 5, 20];
      NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K MATCHES %@", attributeName, attributeValue];
      [fetchRequest setPredicate:predicate];
      

      乔斯。

      【讨论】:

        【解决方案4】:

        斯威夫特:

        返回 4 到 7 个字符的字符串。

        NSPredicate(format: "text MATCHES %@", ".{4,7}")
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-04
          • 2020-05-26
          • 1970-01-01
          • 2013-11-22
          • 1970-01-01
          • 2022-08-08
          相关资源
          最近更新 更多