By ordering the NSString NSArray in a specific order

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

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

+3


source to share


2 answers


NSArray has several sorting functions. Three you can consider are as follows:

- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr

- (NSArray *)sortedArrayUsingSelector:(SEL)comparator

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

I think you can find a second selector-based comparator that's the easiest to use to get started. See 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 might be overkill, but here's a good article describing it:

How do I sort NSMutableArray using sortedArrayUsingDescriptors?

+1


source


Short answer: Yes!

That's how...

Since there are two pieces of information that you need to know about your value (importance and value itself), you must create an object with these two important pieces of information, and then store them in an array similar to how you store your strings. This makes it easy if, say, you want to change the "severity" after a while with minimal 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 the 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

      

+2


source







All Articles