-
Notifications
You must be signed in to change notification settings - Fork 49
/
SCSortedArrayController.m
103 lines (55 loc) · 2.21 KB
/
SCSortedArrayController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//
// SCSortedArrayController.m
// cfxr
//
// By http://shanecrawford.org/2008/37/sorting-a-coredata-backed-nsarraycontroller/
//
#import "SCSortedArrayController.h"
@implementation SCSortedArrayController
- (void)awakeFromNib
{
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"index"
ascending:YES];
[self setSortDescriptors:[NSArray arrayWithObject:sort]];
[super awakeFromNib];
}
- (void)remove:(id)sender
{
[super remove:sender];
[self reindexEntries];
}- (void)insertObject:(id)object atArrangedObjectIndex:(NSUInteger)index
{
[object setValue:[NSNumber numberWithInt:index] forKey:@"index"];
[super insertObject:object atArrangedObjectIndex:index];
[self reindexEntries];
}
- (void) reindexEntries
{
// Note: use a temporary array since modifying an item in arrangedObjects
// directly will cause the sort to trigger thus throwing off
// the re-indexing.
int count = [[self arrangedObjects] count];
NSArray *tmpArray = [NSArray arrayWithArray:[self arrangedObjects]];
for(int ndx = 0; ndx < count ; ndx++){
id entry = [tmpArray objectAtIndex:ndx];
[entry setValue:[NSNumber numberWithInt:ndx] forKey:@"index"];
}
}
- (NSArray *)arrangeObjects:(NSArray *)objects
{
// Note: at this point the data objects are CoreData faults and thus contain
// no real data. So, go ahead and batch fault (load) the data for use
// in sorting
NSError *error = nil;
NSManagedObjectContext *moc = [appDelegate managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Sound"
inManagedObjectContext:moc];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setReturnsObjectsAsFaults:NO];
[request setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self IN %@", objects];
[request setPredicate:predicate];
[moc executeFetchRequest:request error:&error]; NSArray *arranged = [super arrangeObjects:objects];
return arranged;
}
@end