3

I have a NSString in an NSArray and I wanted to order this string/fields based on how important it is. So say the string is B, H, A, Q, Z, L, M, O.

I wanted it to be always sorted as A, Q, Z, B, H, O, L, M. This is a predefined set of rule. How do I do this? Can this be done using NSSortDescriptor?

adit
  • 32,574
  • 72
  • 229
  • 373

2 Answers2

2

The short answer: Yes!

And here's how...

Since there are two pieces of information you need to know about your value (the importance and the value itself), you should create an object with these two important pieces of information, then store in an array similar to the way you store your strings. This makes it simple if, say, you want to change the 'importance' some time later with very little effort:

@interface MyObject : NSObject
@property (nonatomic, readwrite) NSInteger sortOrder;
@property (nonatomic, retain) NSString *value;
@end

@implementation MyObject
@synthesize sortOrder;
@synthesize value;
-(NSString *)description
{
   //...so I can see the values in console should I NSLog() it
   return [NSString stringWithFormat:@"sortOrder=%i, value=%@", self.sortOrder, self.value];
}
-(void)dealloc
{
    self.value = nil;
    [super dealloc];
}
@end

Add your objects to an array. Then sort:

NSMutableArray *myArrayOfObjects = [NSMutableArray array];

//Add your objects
MyObject *obj = [[[MyObject alloc] init] autorelease];
obj.sortOrder = 1;
obj.value = @"A";
[myArrayOfObjects addObject:obj];

obj = [[[MyObject alloc] init] autorelease];
obj.sortOrder = 2;
obj.value = @"Q";
[myArrayOfObjects addObject:obj];

//Sort the objects according to importance (sortOrder in this case)
NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"sortOrder" ascending:YES] autorelease];
NSArray *sortedArray = [myArrayOfObjects sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSLog(sortedArray);  //<--See for yourself that they are sorted
Jeremy
  • 8,902
  • 2
  • 36
  • 44
1

NSArray has several sort functions. Three you might consider are:

- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr

- (NSArray *)sortedArrayUsingSelector:(SEL)comparator

- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context

I think you might find the second, selector-based comparator the easiest to use to get started. See the docs here:

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/occ/instm/NSArray/sortedArrayUsingSelector:

EDIT:

I think using NSSortDescriptor may be overkill, but here is a good post describing it:

How to sort NSMutableArray using sortedArrayUsingDescriptors?

Community
  • 1
  • 1
par
  • 17,361
  • 4
  • 65
  • 80