iOS - NSFetchRequest:按字符串长度排序

iOS - NSFetchRequest: sorting for string length

我正在尝试根据 'name' 属性 的长度对核心数据实体进行排序,这是一个字符串。

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 属性是新奥尔良、纽约和纽卡斯尔,则结果数组 query = "New"应该是纽约、纽卡斯尔和新奥尔良。

我错过了什么吗?

谢谢, 丹

不幸的是,您无法访问 CoreData 中 NSString 的 .length 和其他属性,

我建议添加另一个 属性 ( @属性 (nonatomic, retain) NSNumber * nameLength; ) 到你的 ManagedObject class ,保存文本的长度和使用这个属性对数据进行排序,更新名称后,更新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);
    }
}