-
Notifications
You must be signed in to change notification settings - Fork 0
/
LXCoreDataOperation.m
85 lines (69 loc) · 2.26 KB
/
LXCoreDataOperation.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
//
// LXCoreDataOperation.m
// LXKit
//
// Created by Luke Iannini on 8/1/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "LXCoreDataOperation.h"
@interface LXCoreDataOperation ()
@property (nonatomic, retain, readwrite) NSManagedObjectContext *insertionContext;
@end
@implementation LXCoreDataOperation
@synthesize insertionContext, insertionBlock, mainContext;
- (void)dealloc
{
[insertionContext release];
[mainContext release];
[insertionBlock release];
[super dealloc];
}
+ (id)operationWithMainContext:(NSManagedObjectContext *)mainContext
block:(LXCoreDataBlock)insertionBlock;
{
LXCoreDataOperation *operation = [[[self alloc] init] autorelease];
operation.mainContext = mainContext;
operation.insertionBlock = insertionBlock;
return operation;
}
- (void)main
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(insertionContextDidSave:)
name:NSManagedObjectContextDidSaveNotification
object:self.insertionContext];
[self performOperation];
if (self.insertionBlock)
{
self.insertionBlock(self.insertionContext);
}
NSError *error = nil;
BOOL success = [self.insertionContext save:&error];
if (!success)
{
NSLog(@"Error saving insert operation: %@", error);
}
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSManagedObjectContextDidSaveNotification
object:insertionContext];
}
- (void)performOperation
{
// To override in subclass
}
- (void)insertionContextDidSave:(NSNotification *)notification
{
dispatch_sync(dispatch_get_main_queue(), ^(void) {
[self.mainContext mergeChangesFromContextDidSaveNotification:notification];
});
}
- (NSManagedObjectContext *)insertionContext
{
if (!insertionContext)
{
insertionContext = [[NSManagedObjectContext alloc] init];
[insertionContext setPersistentStoreCoordinator:[self.mainContext persistentStoreCoordinator]];
}
return insertionContext;
}
@end