views:

138

answers:

1

I expected the code below to return the objects in imageSet as a sorted array. Instead, there's no difference in the ordering before and after.

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"imageID" ascending:YES];
NSSet *imageSet = collection.images;

for (CBImage *image in imageSet) {
    NSLog(@"imageID in Set: %@",image.imageID);
}

NSArray *imageArray = [[imageSet allObjects] sortedArrayUsingDescriptors:(descriptor, nil)];    
[descriptor release];

for (CBImage *image in imageArray) {
    NSLog(@"imageID in Array: %@",image.imageID);
}

Fwiw, CBImage is defined in my core data model. I don't know why sorting on managed objects would work any differently than on "regular" objects, but maybe it matters.

As proof that @"imageID" should work as the key for the descriptor, here's what the two log loops above output for one of the sets I'm iterating through:

2010-05-05 00:49:52.876 Cover Browser[38678:207] imageID in Array: 360339
2010-05-05 00:49:52.876 Cover Browser[38678:207] imageID in Array: 360337
2010-05-05 00:49:52.877 Cover Browser[38678:207] imageID in Array: 360338
2010-05-05 00:49:52.878 Cover Browser[38678:207] imageID in Array: 360336
2010-05-05 00:49:52.879 Cover Browser[38678:207] imageID in Array: 360335

... For extra credit, I'd love to get a general solution to troubleshooting NSSortDescriptor troubles (esp. if it also applies to troubleshooting NSPredicate). The functionality of these things seems totally opaque to me and consequently debugging takes forever.

+2  A: 

I think that the problem is this line:

... [[imageSet allObjects] sortedArrayUsingDescriptors:(descriptor, nil)];

In C (and by extension, Objective-C), the comma operator works by evaluating each sub-expression for its side-effects, and using the result of the last sub-expression as the result of the expression as a whole. Therefore,

(descriptor, nil)

evaluates to just nil. There is no built-in way to make a static NSArray instance (unlike using @"str" to create static NSString instances for example). If you want to create an NSArray, you need to do it like this:

... [[imageSet allObjects] sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor, nil]];

Or, equivalently

... [[imageSet allObjects] sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];
dreamlax
Thanks, dreamlax! I knew that once, but it's easy to forget that commas are even operators to begin with. I really appreciate this: hours of (additional) angst avoided.
clozach