如何使用另一个包含对象有序键的 NSArray 对对象的 NSArray 进行排序?

发布于 2024-12-28 03:35:17 字数 448 浏览 5 评论 0原文

例如,如果我有一个对象:

@interface MyObject
{
    __id;
    __data;
}

并且我有一个此类对象的 NSArray:

id=4
data=Apple
id=5
data=Banana
id=6
data=Orange

我还有一个 ids 的 NSArray:

{"5", "4", "6"}

现在我想按 ids 对对象数组进行排序,使其符合第二个数组中的顺序,因此结果应该是:

id=5
data=Banana
id=4
data=Apple
id=6
data=Orange

可能吗(在 iPhone 的 ObjC 中)?最有效的方法是什么?

谢谢!

for example, if I have an object:

@interface MyObject
{
    __id;
    __data;
}

and I have an NSArray of such object:

id=4
data=Apple
id=5
data=Banana
id=6
data=Orange

I also have an NSArray of ids:

{"5", "4", "6"}

now I want to sort the array of objects by ids to be in the order in the second array, so the result should be:

id=5
data=Banana
id=4
data=Apple
id=6
data=Orange

Is it possible(in ObjC for iPhone)? What is the most efficient way?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岛徒 2025-01-04 03:35:17

您可以使用 NSArray 类的 - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr 函数。

您应该编写自己的比较器块,该块将根据 ids 数组中 id 的位置返回排序 - 即,当 idA 距离数组开头比 idB 更远时,返回 NSOrderedAscending。

希望这有帮助。

You can use - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr function of the NSArray class.

You should write your own comparator block that will return ordering depending on the position of id in the ids array - ie return NSOrderedAscending when idA is further from the start of the array than idB.

Hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文