Reputation: 99
Is there any way I can rearrange the sections of a Table View that uses Core Data, without using a Sort Descriptor?
The kind of sort I need is not alphabetical, and it'll vary on time (I have read that, using Core Data, you can't use custom selectors for a sort descriptor, so the default ones doesn't help me).
I have a method that gets called when a "section reordering" should happen, and I wonder if there's some kind of "index vector" I can modify, so the sections get ordered by that index, or something similar.
Thanks for the help!
Upvotes: 0
Views: 336
Reputation: 80265
You have two options here:
1
Anything you want to order in core data (and, by extension, using a NSFetchedResultsController
) you will need to somehow model in your data and use sort descriptors.
You state (but do not explain) that "the default [sort descriptor] doesn't help" you. I suppose that means that with the data contained in your model is not sufficient to do the reordering. In this case you would have to introduce a new attribute to the entity in question. That might sound like too much effort, but often it is not that bad.
2
You can change the datasource
of your table view from the fetched results controller to your own scheme (e.g. with arrays). Of course, there are memory implications, but this might just be the easiest way.
EDIT
After you restated the problem (circular vector sorting) here is a suggestion: you can use sortDescriptorWithKey:ascending:comparator:
to construct a sort descriptor that delivers exactly the result you want. (warning: untested code)
int centerNumber = 2; // or whatever your method returns
NSSortDescriptor *descriptor = [NSSortDescriptor
sortDescriptorWithKey:@"number"
ascending:YES
comparator:^(int a, int b) {
NSComparisonResult r;
if (a == b) r = NSOrderedSame;
else if (a == centerNumber) r = NSOrderedAscending;
else if (b == centerNumber) r = NSOrderedDescending;
else if (abs(a-c) == abs(b-c))
if (a<b) r = NSOrderedDescending;
else r = NSOrderedAscending;
else
if (abs(a-c) > abs(b-c)) r = NSOrderedAscending;
else r = NSOrderedDescending;
return r;
}];
Let me know if it works.
EDIT 2
If you need NSNumber (which is how your data is stored most likely), maybe this works:
...^(id x, id y) {
int a = [x intValue];
int b = [y intValue];
...
}...
Final Edit
If the comparator does not work, insert NSComparisonResult
as the result type:
...comparator:^NSComparisonResult(id x, id y){....
Upvotes: 1