【问题标题】:sorting objects in NSMutableArray在 NSMutableArray 中排序对象
【发布时间】:2012-05-16 04:58:49
【问题描述】:

我的 NSMutableArray 包含 GroupUser 对象的列表:

@interface GroupUser : NSObject {

    NSString *groupUser_name;//user name
    NSString *groupUser_customMsg;
    NSString *groupUser_emailId;
    NSString *groupUser_groupName;
    NSString *groupUser_aliasName;
    int groupUser_imageId;
    int groupUser_state;//whether user is online( value 0) offline(value 1) or busy(value 2)
    int groupUser_type;             
}

现在我想对列表进行排序: 1.基于groupUser_state 2. 基于groupUser_name

例如:: 1. Sam 离线(值 1) 2.拉维在线(值0) 3.阿米特在线(值0) 4.恒河在线(值0) 5.杜尔加离线(值1)

排序后的输出应该是:: 1.阿米特在线 2.恒河在线 3.拉维在线 4.杜尔加离线 5. 山姆离线

通过提供相同的代码来帮助我.. 提前谢谢

【问题讨论】:

标签: iphone


【解决方案1】:
NSSortDescriptor *desc=[NSSortDescriptor  sortDescriptorWithKey:@"groupUser_state" ascending:YES];
NSArray *yourArray;
[yourArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:desc]];

【讨论】:

  • 感谢每一位回答的人。在所有链接的帮助下,我得到了我的解决方案 NSArray sortedArray; NSSortDescriptor stateDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"groupUser_state" descending:NO] autorelease]; NSSortDescriptor* nameDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"groupUser_name" 升序:YES] autorelease]; NSArray* sortDescriptors = [NSArray arrayWithObjects:stateDescriptor, nameDescriptor, nil]; sortedArray = [[m_appDelegate groupUsersList] sortedArrayUsingDescriptors:sortDescriptors];随意评论这个解决方案..如果在任何意义上我可以改进它
  • @Saraswati 添加这样的代码时,最好编辑您的原始问题并将解决方案添加到末尾或添加您自己的答案,以便人们可以真正阅读它。
【解决方案2】:

或者,您可以调用 NSMutableArray 的 -sortUsingSelector:,但是您的自定义对象应该提供一种方法来进行比较,如下所示:

- (NSComparisonResult) compareSomeVariable:(GroupUser*) otherUser
{
    // Assumes ivar _someVariable is numeric; use NSString methods to compare
    // strings, etc.

    if(this->_someVariable < otherObject->_someVariable){
        return NSOrderedAscending;
    }
    else if(this->_someVariable > otherObject->_someVariable){
        return NSOrderedDescending;
    }
    else{
        return NSOrderedSame;
    }
}

然后像这样对它们进行排序:

[array sortUsingSelector:@selector(compareSomeVariable:)];

缺点是你必须在你的类中定义这个自定义方法。 您可以有几种不同的方法来根据不同的标准对对象进行排序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 2012-01-17
    • 1970-01-01
    相关资源
    最近更新 更多