forked from triplef/LastHistory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LHOperation.m
109 lines (86 loc) · 2.41 KB
/
LHOperation.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
104
105
106
107
108
109
//
// LHOperation.m
// LastHistory
//
// Created by Frederik Seiffert on 20.11.09.
// Copyright 2009 Frederik Seiffert. All rights reserved.
//
#import "LHOperation.h"
#import "LHDocument.h"
@implementation LHOperation
@synthesize document=_document;
@synthesize context=_context;
@synthesize progressMessage=_progressMessage;
@synthesize progress=_progress;
@synthesize progressIndeterminate=_progressIndeterminate;
- (instancetype)initWithDocument:(LHDocument *)document
{
self = [super init];
if (self != nil) {
_document = document;
[self addObserver:self forKeyPath:@"isExecuting" options:0 context:NULL];
[self addObserver:self forKeyPath:@"isFinished" options:0 context:NULL];
self.progressIndeterminate = YES;
}
return self;
}
- (NSManagedObjectContext *)context
{
if (!_context)
{
// setup managed object context (note: this needs to happen on processing thread!)
NSAssert(![NSThread isMainThread], @"NSOperation MOC created on main thread");
_context = [[NSManagedObjectContext alloc] init];
_context.persistentStoreCoordinator = (self.document).managedObjectContext.persistentStoreCoordinator;
[_context setUndoManager:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(contextDidChange:)
name:NSManagedObjectContextDidSaveNotification
object:_context];
}
return _context;
}
- (void)finalize
{
[self removeObserver:self forKeyPath:@"isExecuting"];
[self removeObserver:self forKeyPath:@"isFinished"];
[super finalize];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"isExecuting"] || [keyPath isEqualToString:@"isFinished"])
{
[self.document performSelectorOnMainThread:@selector(updateOperation:)
withObject:self
waitUntilDone:NO];
}
}
- (void)contextDidChange:(NSNotification *)notification
{
// merge changes with document context
[_document performSelectorOnMainThread:@selector(mergeChanges:)
withObject:notification
waitUntilDone:NO];
}
- (BOOL)saveContext
{
NSError *error = nil;
BOOL result = [_context save:&error];
if (!result)
[self.document presentError:error];
return result;
}
- (void)process
{
// perform task
}
- (void)main
{
@try {
[self process];
}
@catch (NSException *e) {
NSLog(@"Error in %@: %@", self.className, e);
}
}
@end