如何根据对象的属性对数组进行排序?

发布于 2024-12-25 18:16:59 字数 174 浏览 3 评论 0原文

我有一个“通用对象”的 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 技术交流群。

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

发布评论

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

评论(1

别在捏我脸啦 2025-01-01 18:16:59

您需要定义一个自定义排序函数,然后将其传递给允许自定义排序的 NSArray 方法。例如,使用 sortedArrayUsingFunction:context:,你可以这样写(假设你的类型是 NSString 实例):

NSInteger customSort(id obj1, id obj2, void *context) {
    NSString * type1 = [obj1 type];
    NSString * type2 = [obj2 type];

    NSArray * order = [NSArray arrayWithObjects:@"topic", @"users", @"questions", nil];

    if([type1 isEqualToString:type2]) {
        return NSOrderedSame; // same type
    } else if([order indexOfObject:type1] < [order indexOfObject:type2]) {
        return NSOrderedDescending; // the first type is preferred
    } else {
        return NSOrderedAscending; // the second type is preferred
    }   
}   

// later...

NSArray * sortedArray = [myGenericArray sortedArrayUsingFunction:customSort
                                                         context:NULL];

如果你的类型不是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):

NSInteger customSort(id obj1, id obj2, void *context) {
    NSString * type1 = [obj1 type];
    NSString * type2 = [obj2 type];

    NSArray * order = [NSArray arrayWithObjects:@"topic", @"users", @"questions", nil];

    if([type1 isEqualToString:type2]) {
        return NSOrderedSame; // same type
    } else if([order indexOfObject:type1] < [order indexOfObject:type2]) {
        return NSOrderedDescending; // the first type is preferred
    } else {
        return NSOrderedAscending; // the second type is preferred
    }   
}   

// later...

NSArray * sortedArray = [myGenericArray sortedArrayUsingFunction:customSort
                                                         context:NULL];

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 the order array entirely.

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