2009-12-04 86 views
28

我有一个关于排序的问题NSMutableArray。我可以使用sortedArrayUsingDescriptors:方法使用对象对数组进行排序。如何使用sortedArrayUsingDescriptors对NSMutableArray进行排序?

比如我的places在那里我有一个属性frequency(int值)的NSMutableArray,我要作为排序依据frequency降,但我不知道如何正确使用它。

作为钥匙我在initWithKey上做了什么?

我的目标place包含:

NSString * name; 
NSString * address; 
NSString * frequency; 
NSString * type; 

NSMutableArray * places; 

... populate array with objects ... 

NSSortDescriptor * sortByFrequency = 
    [[[NSSortDescriptor alloc] initWithKey:@"????????" ascending:NO] autorelease]; 

NSArray * descriptors = [NSArray arrayWithObject:sortByFrequency]; 
NSArray * sorted = [x sortedArrayUsingDescriptors:descriptors]; 
+6

唉!这很难理解。宝贝开发者请在你的问题中使用标点符号(主要是句号和逗号)。 – pmg 2009-12-04 00:24:00

+3

你说这个“frecuency”是一个int值,但你的代码说它是一个NSString。请注意清楚地说出你的问题。 – Chuck 2009-12-04 00:36:37

回答

1

下面是如何将排序一个NSMutableArray:

NSMutableArray *numberSort =[[NSMutableArray alloc] init]; 

    while ((key = [enumerator nextObject])) { 
     //(NSNumber *)integer = [key integerValue]; 
     [numberSort addObject:[NSNumber numberWithInt:[key intValue]]]; 
     // code that uses the returned key 
    } 


    NSArray *stringSort = [numberSort sortedArrayUsingSelector:@selector(compare:)]; 
    enumerator = [stringSort objectEnumerator]; 
    NSNumber *intKey; 

    NSMutableArray *backToString =[[NSMutableArray alloc] init]; 

    while ((intKey = [enumerator nextObject])) { 
     //(NSNumber *)integer = [key integerValue]; 
     [backToString addObject:[intKey stringValue]]; 
     // code that uses the returned key 
2

“密钥” 是你对象的方法(你的数组“x”)的元素,它返回你想要排序的东西。所以在这种情况下,你说你想按“频率”排序。然后,你所要做的就是使用返回频率的方法的名称作为键。

+0

虽然它必须是数字类型,例如'int'(最好是'unsigned'),'NSUInteger','double'或'NSNumber *'。以频率值作为字符串,它们不会按数字排序(不是没有自定义比较器,无论如何)。 – 2009-12-05 06:51:16

110

排序你,你的对象数组:

  1. 设置NSSortDescriptor - 你的变量作为键设置描述符排序加选择使用的名称将在琴键上执行
  2. 获得描述符的数组使用NSSortDescriptor你已经设置
  3. 排序基于这些描述符

这里有两个例子,一个使用阵列NSDictionaryNSString/NSNumber值排序NSNumber,另一个使用自定义类与排序在两个NSString字段。

按照Sorting and Filtering NSArray Objects在Cocoa编程主题中看到更多的例子和解释。

这是在GNUstep的做它应该工作一样可可 - 该代码是完全一样的 - 当我坐在我的Mac面前我会尝试:

NSString * NAME  = @"name"; 
NSString * ADDRESS = @"address"; 
NSString * FREQUENCY = @"frequency"; 
NSString * TYPE  = @"type"; 

NSMutableArray * array = [NSMutableArray array]; 

NSDictionary * dict; 

dict = [NSDictionary dictionaryWithObjectsAndKeys: 
      @"Alehandro", NAME, @"Sydney", ADDRESS, 
      [NSNumber numberWithInt:100], FREQUENCY, 
      @"T", TYPE, nil]; 
[array addObject:dict]; 

dict = [NSDictionary dictionaryWithObjectsAndKeys: 
      @"Xentro", NAME, @"Melbourne", ADDRESS, 
      [NSNumber numberWithInt:50], FREQUENCY, 
      @"X", TYPE, nil]; 
[array addObject:dict]; 

dict = [NSDictionary dictionaryWithObjectsAndKeys: 
      @"John", NAME, @"Perth", ADDRESS, 
      [NSNumber numberWithInt:75], 
      FREQUENCY, @"A", TYPE, nil]; 
[array addObject:dict]; 

dict = [NSDictionary dictionaryWithObjectsAndKeys: 
      @"Fjord", NAME, @"Brisbane", ADDRESS, 
      [NSNumber numberWithInt:20], FREQUENCY, 
      @"B", TYPE, nil]; 
[array addObject:dict]; 
:使用 NSStringNSNumber值与 NSNumber值排序

第一示例


排序使用部分描述符与所述频率字段,它是NSNumber

NSSortDescriptor * frequencyDescriptor = 
    [[[NSSortDescriptor alloc] initWithKey:FREQUENCY 
           ascending:YES] autorelease]; 

id obj; 
NSEnumerator * enumerator = [array objectEnumerator]; 
while ((obj = [enumerator nextObject])) NSLog(@"%@", obj); 

NSArray * descriptors = 
    [NSArray arrayWithObjects:frequencyDescriptor, nil]; 
NSArray * sortedArray = 
    [array sortedArrayUsingDescriptors:descriptors]; 

NSLog(@"\nSorted ..."); 

enumerator = [sortedArray objectEnumerator]; 
while ((obj = [enumerator nextObject])) NSLog(@"%@", obj); 

OUTPUT - 用频域来分类:

2009-12-04 x[1] {address = Sydney; frequency = 100; name = Alehandro; type = T; } 
2009-12-04 x[1] {address = Melbourne; frequency = 50; name = Xentro; type = X; } 
2009-12-04 x[1] {address = Perth; frequency = 75; name = John; type = A; } 
2009-12-04 x[1] {address = Brisbane; frequency = 20; name = Fjord; type = B; } 
2009-12-04 x[1] 
Sorted ... 
2009-12-04 x[1] {address = Brisbane; frequency = 20; name = Fjord; type = B; } 
2009-12-04 x[1] {address = Melbourne; frequency = 50; name = Xentro; type = X; } 
2009-12-04 x[1] {address = Perth; frequency = 75; name = John; type = A; } 
2009-12-04 x[1] {address = Sydney; frequency = 100; name = Alehandro; type = T; } 


第二个自定义类和对两个NSString变量进行排序的示例。

数组进行排序(见A类在底部):

NSMutableArray * array = [NSMutableArray array]; 
[array addObject:[[A alloc] initWithFirstName:@"Alehandro" 
            lastName:@"Xentro" 
              age:[NSNumber numberWithInt:40]]]; 
[array addObject:[[A alloc] initWithFirstName:@"John" 
            lastName:@"Smith" 
              age:[NSNumber numberWithInt:30]]]; 
[array addObject:[[A alloc] initWithFirstName:@"John" 
            lastName:@"Smyth" 
              age:[NSNumber numberWithInt:25]]]; 
[array addObject:[[A alloc] initWithFirstName:@"Torro" 
            lastName:@"Ola" 
              age:[NSNumber numberWithInt:45]]]; 
[array addObject:[[A alloc] initWithFirstName:@"Alehandro" 
            lastName:@"Bento" 
              age:[NSNumber numberWithInt:41]]]; 
[array addObject:[[A alloc] initWithFirstName:@"Alehandro" 
            lastName:@"Axel" 
              age:[NSNumber numberWithInt:41]]]; 

分拣部,排序按LastName然后姓:

NSString * LASTNAME = @"lastName"; 
NSString * FIRSTNAME = @"firstName"; 

NSSortDescriptor *lastDescriptor = 
    [[[NSSortDescriptor alloc] 
     initWithKey:LASTNAME 
      ascending:YES 
      selector:@selector(localizedCaseInsensitiveCompare:)] autorelease]; 

NSSortDescriptor *firstDescriptor = 
    [[[NSSortDescriptor alloc] 
     initWithKey:FIRSTNAME 
      ascending:YES 
      selector:@selector(localizedCaseInsensitiveCompare:)] autorelease]; 

NSArray * descriptors = 
    [NSArray arrayWithObjects:lastDescriptor, firstDescriptor, nil]; 
NSArray * sortedArray = 
    [array sortedArrayUsingDescriptors:descriptors]; 

打印结果:

NSLog(@"\nSorted ..."); 

enumerator = [sortedArray objectEnumerator]; 
while ((obj = [enumerator nextObject])) NSLog(@"%@", obj); 

结果(前和排序后):A延伸NSObject

2009-12-04 00:52:16.637 x[11375] Alehandro, Xentro, age:40 
2009-12-04 00:52:16.644 x[11375] John, Smith, age:30 
2009-12-04 00:52:16.644 x[11375] John, Smyth, age:25 
2009-12-04 00:52:16.644 x[11375] Torro, Ola, age:45 
2009-12-04 00:52:16.645 x[11375] Alehandro, Bento, age:41 
2009-12-04 00:52:16.645 x[11375] Alehandro, Axel, age:41 
2009-12-04 00:52:16.645 x[11375] 
Sorted ... 
2009-12-04 00:52:16.645 x[11375] Alehandro, Axel, age:41 
2009-12-04 00:52:16.645 x[11375] Alehandro, Bento, age:41 
2009-12-04 00:52:16.645 x[11375] Torro, Ola, age:45 
2009-12-04 00:52:16.645 x[11375] John, Smith, age:30 
2009-12-04 00:52:16.645 x[11375] John, Smyth, age:25 
2009-12-04 00:52:16.645 x[11375] Alehandro, Xentro, age:40 

类 - 这里没有什么特别:

#import <Foundation/Foundation.h> 

@interface A : NSObject 
{ 
    NSString * firstName; 
    NSString * lastName; 
    NSNumber * age; 
} 

- (id)initWithFirstName:(NSString*)aFirstName 
       lastName:(NSString*)aLastName 
        age:(NSNumber*)anAge; 

-(NSString*)description; 
+(NSString*)action; 

@end 

实现:

#import <Foundation/Foundation.h> 
#import "A.h" 

@implementation A 

- (id)init 
{ 
    return [self initWithFirstName:@"N/A" 
          lastName:@"N/A" 
           age:0]; 
} 

- (id)initWithFirstName:(NSString*)aFirstName 
       lastName:(NSString*)aLastName 
        age:(NSNumber*)anAge 
{ 
    self = [super init]; 
    if (!self) return nil; 

    firstName = [aFirstName copy]; 
    lastName = [aLastName copy]; 
    age = [anAge copy]; 

    return self; 
} 

- (void)dealloc 
{ 
    [firstName release]; 
    [lastName release]; 
    [age release]; 
    [super release]; 
} 

- (NSString *) description 
{ 
    return [NSString stringWithFormat: @"%@, %@, age:%@", 
             firstName, lastName, age]; 
} 
@end 
+10

谢谢你这样详细的答案! – DonnaLea 2011-03-09 04:54:09

+1

谢谢你stefanB。非常感谢:) – 2011-05-11 07:14:56

+0

+1,非常感谢Descriptive Answer :)帮了我很多:D – mAc 2012-07-18 14:03:27

相关问题