forked from Awful/Awful.app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNSManagedObject+Awful.m
More file actions
83 lines (75 loc) · 2.8 KB
/
NSManagedObject+Awful.m
File metadata and controls
83 lines (75 loc) · 2.8 KB
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
//
// NSManagedObject+Awful.m
// Awful
//
// Created by Nolan Waite on 2012-10-10.
// Copyright (c) 2012 Regular Berry Software LLC. All rights reserved.
//
#import "NSManagedObject+Awful.h"
#import "AwfulDataStack.h"
#import "AwfulModels.h"
@implementation NSManagedObject (Awful)
+ (NSArray *)fetchAll
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:[(Class)self entityName]];
NSError *error;
NSArray *all = [[AwfulDataStack sharedDataStack].context executeFetchRequest:request
error:&error];
if (!all) {
NSLog(@"error fetching all %@: %@", self, error);
}
return all;
}
+ (NSArray *)fetchAllMatchingPredicate:(id)format, ...
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:[(Class)self entityName]];
if ([format isKindOfClass:[NSPredicate class]]) {
[request setPredicate:(NSPredicate *)format];
} else {
va_list args;
va_start(args, format);
[request setPredicate:[NSPredicate predicateWithFormat:format arguments:args]];
va_end(args);
}
NSError *error;
NSArray *matches = [[AwfulDataStack sharedDataStack].context executeFetchRequest:request
error:&error];
if (!matches) {
NSLog(@"error fetching %@ matching %@: %@", self, [request predicate], error);
}
return matches;
}
+ (instancetype)firstMatchingPredicate:(id)formatOrPredicate, ...
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:[(Class)self entityName]];
if ([formatOrPredicate isKindOfClass:[NSPredicate class]]) {
[request setPredicate:(NSPredicate *)formatOrPredicate];
} else {
va_list args;
va_start(args, formatOrPredicate);
[request setPredicate:[NSPredicate predicateWithFormat:formatOrPredicate arguments:args]];
va_end(args);
}
NSError *error;
NSArray *matches = [[AwfulDataStack sharedDataStack].context executeFetchRequest:request
error:&error];
if (!matches) {
NSLog(@"error fetching %@ matching %@: %@", self, [request predicate], error);
}
return [matches count] > 0 ? matches[0] : nil;
}
+ (void)deleteAllMatchingPredicate:(NSString *)format, ...
{
va_list args;
va_start(args, format);
NSPredicate *predicate = [NSPredicate predicateWithFormat:format arguments:args];
va_end(args);
for (NSManagedObject *dying in [self fetchAllMatchingPredicate:predicate]) {
[dying.managedObjectContext deleteObject:dying];
}
}
+ (instancetype)insertNew
{
return [(Class)self insertInManagedObjectContext:[AwfulDataStack sharedDataStack].context];
}
@end