forked from objcio/issue-4-full-core-data-application
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathItem.m
64 lines (53 loc) · 1.8 KB
/
Item.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
//
// Item.m
// NestedTodoList
//
// Created by Chris Eidhof on 8/14/13.
// Copyright (c) 2013 Chris Eidhof. All rights reserved.
//
#import "Item.h"
#import "Item.h"
@implementation Item
@dynamic title;
@dynamic parent;
@dynamic children;
@dynamic order;
+ (instancetype)insertItemWithTitle:(NSString*)title
parent:(Item*)parent
inManagedObjectContext:(NSManagedObjectContext *)managedObjectContext
{
NSUInteger order = parent.numberOfChildren;
Item* item = [NSEntityDescription insertNewObjectForEntityForName:self.entityName
inManagedObjectContext:managedObjectContext];
item.title = title;
item.parent = parent;
item.order = @(order);
return item;
}
+ (NSString*)entityName
{
return @"Item";
}
- (NSUInteger)numberOfChildren
{
return self.children.count;
}
- (NSFetchedResultsController*)childrenFetchedResultsController
{
NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:[self.class entityName]];
request.predicate = [NSPredicate predicateWithFormat:@"parent = %@", self];
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"order" ascending:YES]];
return [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
}
- (void)prepareForDeletion
{
if (self.parent.isDeleted) return;
NSSet* siblings = self.parent.children;
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"order > %@", self.order];
NSSet* itemsAfterSelf = [siblings filteredSetUsingPredicate:predicate];
[itemsAfterSelf enumerateObjectsUsingBlock:^(Item* sibling, BOOL* stop)
{
sibling.order = @(sibling.order.integerValue - 1);
}];
}
@end