Duck
Duck

Reputation: 36003

iPhone - creating a define for a NSSortDescriptor... is that possible?

I use this a lot

NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:nil 
                       ascending:YES 
                       comparator:^(id obj1, id obj2) {
                       return [obj1 compare:obj2 options:NSNumericSearch];
                       }];

I would like to create a compiler define like this

#define descriptor [NSSortDescriptor sortDescriptorWithKey:nil 
                       ascending:YES 
                       comparator:^(id obj1, id obj2) {
                       return [obj1 compare:obj2 options:NSNumericSearch];
                      }]

so I can use it on all parts of my code without having to declare it all times and use it on stuff like

mySortedArray = [myArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];

. I have tried this and received a ton of errors from Xcode. Is there a way to define that?

thanks

Upvotes: 1

Views: 419

Answers (3)

Amresh Kumar
Amresh Kumar

Reputation: 1445

The reason what i see for it not to work is that the function
[NSArray sortedArrayUsingDescriptors:];
requires an array as a parameter, however you are passing a NSSortDescriptor directly.
Try using the same as:


myArray = [myArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];

The #define will be


#define descriptor [NSSortDescriptor sortDescriptorWithKey:nil \
                       ascending:YES \
                       comparator:^(id obj1, id obj2) { \
                       return [obj1 compare:obj2 options:NSNumericSearch]; \
                      }]

OR


#define descriptor [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES comparator:^(id obj1, id obj2) { return [obj1 compare:obj2 options:NSNumericSearch]; }]

Upvotes: 1

graver
graver

Reputation: 15213

You were almost there:

#define descriptor [NSSortDescriptor sortDescriptorWithKey:nil \
                                                 ascending:YES \
                                                comparator:^(id obj1, id obj2) { \
                                      return [obj1 compare:obj2 options:NSNumericSearch];}]

Then:

NSArray *sorted = [myArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];

The reason you get errors is because you should use \ when going to a new line. Also -sortedArrayUsingDescriptors requires an array...

Upvotes: 2

Rui Peres
Rui Peres

Reputation: 25917

You can create one of two things:

  1. A category for your NSObjects and there you could define your method.
  2. An util class with a class method that would do what you want.

Depending of your use for your NSSortDescriptor a category could be a good solution. You can always put it to be a NSArray's category instead of a NSObject one.

Upvotes: 1

Related Questions