gpt4 book ai didi

ios - NSSortDescriptor Nil 对象解析

转载 作者:行者123 更新时间:2023-11-29 12:15:34 24 4
gpt4 key购买 nike

我在我的应用程序中使用 Parse,在获取我的对象时,我需要使用 NSSortDescriptor。我可以通过特定字段/属性进行排序,但该排序字段为 nil 的任何对象在结果中排​​在第一位。

我可以让排序字段中的 nil 对象排在最后吗?

最佳答案

很难让零在升序排序中排在最后。我的方法是以下之一:(a) 您编写的基于 block 的 NSComparator 最后强制为空值,或者 (b) 使用 NSSortDescriptor,但暂时或永久替换最大值超出数据范围的空值,或 (c) 使用 NSSortDescriptor,简单排序,然后手动将空值移动到末尾。

如果您没有使用排序描述符,我会采用比较器的想法 (a),如下所示:(假设您正在根据某些属性对 PFObject 进行排序)...

NSComparator comparator = ^(PFObject *objA, PFObject *objB) {
id someProperyA = objA[@"someProperty"];
id someProperyB = objB[@"someProperty"];

// two nulls are equal
if (!somePropertyA && !somePropertyB) return NSOrderedSame;

// any single null is bigger in your world, so sort it last
if (!somePropertyA) return NSOrderedDescending;
if (!somePropertyB) return NSOrderedAscending;

// otherwise use compare, or whatever you were planning to use
// with your NSSortDescriptor
return [somePropertyA compare:somePropertyB];
};

关于ios - NSSortDescriptor Nil 对象解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32121360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com