Reputation: 36003
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
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]];
#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
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
Reputation: 25917
You can create one of two things:
NSObjects
and there you could define your method.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