2012-05-16 45 views
1

我NSMutableArray中包含GroupUser对象的列表:排序对象的NSMutableArray

@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.萨姆离线(值1) 2.拉维在线(值0) 3.阿米特在线(值0) 4.恒河在线(值0) 5.杜尔加离线(值1)

排序后

输出应该是:: 1.阿米特在线 2.恒河在线 3.拉维在线 4.杜尔加离线 萨姆离线

由相同..感谢名单提供代码帮助我提前

+0

看到这个http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it – HarshIT

+0

如果你还没有得到,然后点击http:// bit.ly/LQlR4Z – HarshIT

+0

我已经尝试按名称排序(使用sortedArrayUsingComparator)和它的完成...但我想先按状态排序,然后按名称 – Saraswati

回答

2
NSSortDescriptor *desc=[NSSortDescriptor sortDescriptorWithKey:@"groupUser_state" ascending:YES]; 
NSArray *yourArray; 
[yourArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:desc]]; 
+0

他想按两个字段排序虽然...... – lnafziger

+0

这只是一个例子来解决他的问题 – Allamaprabhu

+0

Thanx每个人回答。在所有链接的帮助下,我得到了我的解决方案 NSArray * sortedArray; NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey:@“groupUser_state”ascending:NO] autorelease]; NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey:@“groupUser_name”ascending:YES] autorelease]; NSArray * sortDescriptors = [NSArray arrayWithObjects:stateDescriptor,nameDescriptor,nil]; sortedArray = [[m_appDelegate groupUsersList] sortedArrayUsingDescriptors:sortDescriptors]; 随时对此解决方案发表评论..如果在任何意义上我都可以改进它 – Saraswati

0

或者,你可以调用的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:)]; 

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

相关问题