【问题标题】:iOS - NSFetchRequest: sorting for string lengthiOS - NSFetchRequest:对字符串长度进行排序
【发布时间】:2015-10-21 08:27:30
【问题描述】:

我正在尝试按其“名称”属性的长度对核心数据实体进行排序,该属性是一个字符串。

Location 是一个包含name 属性(字符串)的NSManagedObject

代码如下:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:[Location entityName]];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] %@", query]];
[fetchRequest setSortDescriptors:@[
    [NSSortDescriptor sortDescriptorWithKey:@"name.length" ascending:YES]]];
[fetchRequest setFetchLimit:3];
NSArray *locations = [context executeFetchRequest:request error:&error];

我希望 name.length KVO 运算符可以工作,但结果排序不正确。

例如:如果模型包含三个Location,其中name 属性是New Orleans、New York 和Newcastle,则query = "New" 的结果数组应该是New York、Newcastle 和New Orleans。

我错过了什么吗?

谢谢, 丹

【问题讨论】:

  • 它的字符串比较,所以这可以帮助你stackoverflow.com/questions/24331566/…
  • 嗨@abrarulhaq,感谢您的回答,但不幸的是,该解决方案正是我正在做的,使用 KVO 运算符(在这种情况下,用户使用的是长度而不是 intValue)。
  • 也许您应该发布完整的搜索 sn-p 以及您的结果和期望。
  • 没问题!问题已更新
  • @DAN - 您应该始终为您的 CoreData 问题提供具体的详细信息。有很多活动部件,并且根据您使用它的方式而有所不同。例如,这个问题中缺少的重要部分是您正在使用 SQLite 存储。其他商店的行为不同。

标签: ios core-data nspredicate nsfetchrequest


【解决方案1】:

很遗憾,您无法在 CoreData 中访问 .length 和 NSString 的其他属性,

我建议在您的 ManagedObject 类中添加另一个属性(@property (nonatomic, retain) NSNumber * nameLength; ),保存文本的长度并使用此属性对数据进行排序,更新名称后,更新nameLength 也是如此,如果您希望 nameLength 自动更新,您可以使用 KVO 或像这样覆盖 setName

- (void)setName:(NSString *)newName
{
    [self willChangeValueForKey:@"name"];
    [self setPrimitiveValue:newName forKey:@"name"];
    [self didChangeValueForKey:@"name"];

    NSUinteger length = newName.length;
    // setName will be called when object is created from the store, make sure you only update it when the actual length is changed, 
    if([self.nameLength unsignedIntegerValue] != length) {
        self.nameLength = @(length);
    }
}

【讨论】:

  • 太糟糕了!谢谢你的帮助:)
  • 最后一件事,您会在模型中添加 nameLength 作为实体的属性吗?
  • 这并不完全正确。您可以在某些商店中访问 .length 属性,但不能在 SQLite 商店中访问。
猜你喜欢
  • 2011-11-26
  • 1970-01-01
  • 2016-04-23
  • 2017-06-21
  • 1970-01-01
  • 2018-02-23
  • 2013-11-05
  • 2017-07-19
  • 1970-01-01
相关资源
最近更新 更多