如何根据对象的属性对数组进行排序?
我有一个“通用对象”的 NSArray,其中包含以下属性
-name
-id
-type (question, topic or user)
如何根据通用对象的类型对该通用对象数组进行排序?例如,我想在顶部显示“主题”类型的所有通用对象,然后是“用户”而不是“问题”
I have a NSArray of 'generic Objects' which contain the following properties
-name
-id
-type (question, topic or user)
How can I sort this array of generic object based on the generic object's type? E.g. I want to display all generic objects of type 'topic' on the top, followed by 'users' than 'questions'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要定义一个自定义排序函数,然后将其传递给允许自定义排序的 NSArray 方法。例如,使用
sortedArrayUsingFunction:context:
,你可以这样写(假设你的类型是 NSString 实例):如果你的类型不是NSStrings,然后根据需要调整函数 - 您可以用实际对象替换
order
数组中的字符串,或者(如果您的类型是枚举的一部分)进行直接比较并消除order
整个数组。You'll need to define a custom sorting function, then pass it to an NSArray method that allows custom sorting. For example, using
sortedArrayUsingFunction:context:
, you might write (assuming your types are NSString instances):If your types aren't NSStrings, then just adapt the function as needed - you could replace the strings in the
order
array with your actual objects, or (if your types are part of an enumeration) do direct comparison and eliminate theorder
array entirely.