-
Notifications
You must be signed in to change notification settings - Fork 0
/
ModelManager.m
77 lines (66 loc) · 2.35 KB
/
ModelManager.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
//
// ModelManager.m
// Tabby
//
// Created by Pablo Collins on 5/30/10.
//
#import "ModelManager.h"
@implementation ModelManager
+ (ModelManager *)sharedInstance {
static ModelManager *me;
if (me == nil) {
me = [[self alloc] init];
}
return me;
}
- (NSManagedObjectContext *)managedObjectContext {
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSURL *storeUrl = [NSURL fileURLWithPath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]
stringByAppendingPathComponent:@"model.sqlite"]];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
return persistentStoreCoordinator;
}
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel != nil) {
return managedObjectModel;
}
managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
return managedObjectModel;
}
- (void)save {
NSError *e;
BOOL ok = [[self managedObjectContext] save:&e];
if (!ok) {
NSLog(@"NSManagedObject: %@", e);
}
}
- (void)delete:(NSManagedObject *)managedObject {
[[self managedObjectContext] deleteObject:managedObject];
[self save];
}
- (NSArray *)findAll:(NSString *)name {
NSFetchRequest *req = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:name inManagedObjectContext:[self managedObjectContext]];
[req setEntity:entity];
NSError *e;
NSArray *out = [[self managedObjectContext] executeFetchRequest:req error:&e];
return out;
}
@end