-
Notifications
You must be signed in to change notification settings - Fork 3
/
MCCDefaults.m
371 lines (299 loc) · 10.8 KB
/
MCCDefaults.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
//
// MCCDefaults.m
// MCCMailCommon
//
// Created by Scott Little on 22/2/14.
// Copyright (c) 2014 Little Known Software, Inc. All rights reserved.
//
#import "MCCDefaults.h"
#import "MCCFileEventQueue.h"
#define PREF_FILE_NOTIFICATIONS (MCCNotifyAboutFileDelete | MCCNotifyAboutFileWrite)
@interface MCC_PREFIXED_NAME(Defaults) ()
@property (assign) BOOL delegateWantsBackups;
@property (strong, atomic) NSDictionary * defaultDictionary;
@property (strong) NSURL * defaultsURL;
@property (strong) NSOperationQueue * prefsAccessQueue;
@property (MCC_WEAK) id<MCC_PREFIXED_NAME(DefaultsDelegate)> delegate;
@property (strong) MCC_PREFIXED_NAME(FileEventQueue) * fileEventQueue;
@property (strong) MCC_PREFIXED_NAME(PathBlock) prefsChangeBlock;
@end
@implementation MCC_PREFIXED_NAME(Defaults)
- (void)dealloc {
#if !__has_feature(objc_arc)
self.defaultDictionary = nil;
self.defaultsURL = nil;
self.prefsAccessQueue = nil;
self.fileEventQueue = nil;
self.prefsChangeBlock = nil;
#endif
MCC_DEALLOC();
}
- (instancetype)initWithDelegate:(id)aDelegate {
self = [super init];
if (self) {
self.delegate = aDelegate;
self.delegateWantsBackups = [aDelegate respondsToSelector:@selector(backupCurrentDefaultsBeforeWriteAtURL:)];
NSBundle * bundle = [NSBundle bundleForClass:[self class]];
NSFileManager * manager = [NSFileManager defaultManager];
NSArray * libraryURLs = [manager URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask];
if ([libraryURLs count]) {
NSURL * tempURL = [[libraryURLs lastObject] URLByAppendingPathComponent:@"Preferences"];
self.defaultsURL = [[tempURL URLByAppendingPathComponent:[bundle bundleIdentifier]] URLByAppendingPathExtension:@"plist"];
}
// Load up initial values and current ones
NSMutableDictionary * defaults = nil;
NSURL * initialDefaultsURL = [bundle URLForResource:@"InitialDefaults" withExtension:@"plist"];
if ([manager fileExistsAtPath:initialDefaultsURL.path]) {
defaults = [[NSDictionary dictionaryWithContentsOfURL:initialDefaultsURL] mutableCopy];
}
else {
defaults = [[NSMutableDictionary alloc] init];
}
NSDictionary * storedDefaults = [self readFromFile];
if (storedDefaults) {
[defaults addEntriesFromDictionary:storedDefaults];
}
else {
storedDefaults = @{};
}
// Allow a subclass to adjust defaults
if ([self.delegate respondsToSelector:@selector(finishPreparingDefaultsWithDictionary:)]) {
[self.delegate finishPreparingDefaultsWithDictionary:defaults];
}
// Set values and the read time
self.defaultDictionary = [NSDictionary dictionaryWithDictionary:defaults];
if (![self.defaultDictionary isEqualToDictionary:storedDefaults]) {
[self writeToFile];
}
MCC_RELEASE(defaults);
self.fileEventQueue = [[MCC_PREFIXED_NAME(FileEventQueue) alloc] init];
MCC_AUTORELEASE(self.fileEventQueue);
MCC_PREFIXED_NAME(Defaults) * blockSelf = self;
self.prefsChangeBlock = ^(MCC_PREFIXED_NAME(FileEventQueue) *anEventQueue, NSString * aNote, NSString * anAffectedPath) {
if ([anAffectedPath isEqualToString:initialDefaultsURL.path]) {
[blockSelf updateFromFileEvent];
}
};
[self.fileEventQueue addAtomicPath:initialDefaultsURL.path withBlock:self.prefsChangeBlock notifyingAbout:PREF_FILE_NOTIFICATIONS];
// Create a serial queue to use
self.prefsAccessQueue = [[NSOperationQueue alloc] init];
MCC_AUTORELEASE(self.prefsAccessQueue);
[self.prefsAccessQueue setMaxConcurrentOperationCount:1];
}
return self;
}
- (NSDictionary *)allDefaults {
NSDictionary * dict = [self.defaultDictionary copy];
MCC_AUTORELEASE(dict);
return dict;
}
#pragma mark - Public Accessors
+ (id)defaultForKey:(NSString *)key {
return [[self sharedDefaults] _defaultForKey:key];
}
+ (id)objectForKey:(NSString *)key {
return [[self sharedDefaults] _defaultForKey:key];
}
+ (BOOL)boolForKey:(NSString *)key {
return [[[self sharedDefaults] _defaultForKey:key] boolValue];
}
+ (NSInteger)integerForKey:(NSString *)key {
return [[[self sharedDefaults] _defaultForKey:key] integerValue];
}
+ (CGFloat)floatForKey:(NSString *)key {
return [[[self sharedDefaults] _defaultForKey:key] floatValue];
}
+ (NSDictionary *)defaultsForKeys:(NSArray *)keys {
return [[self sharedDefaults] _defaultsForKeys:keys];
}
+ (void)setDefault:(id)value forKey:(NSString *)key {
if (!value) {
[[self sharedDefaults] removeDefaultForKeyOnMainThread:key];
}
else {
[[self sharedDefaults] setDefaultsWithDictionaryOnMainThread:@{key: value}];
}
}
+ (id)launchDefaultForKey:(NSString *)key {
return [[self sharedDefaults] _launchDefaultForKey:key];
}
+ (BOOL)launchBoolForKey:(NSString *)key {
return [[[self sharedDefaults] _launchDefaultForKey:key] boolValue];
}
+ (void)setObject:(id)value forKey:(NSString *)key {
[self setDefault:value forKey:key];
}
+ (void)setBool:(BOOL)value forKey:(NSString *)key {
[self setDefault:@(value) forKey:key];
}
+ (void)setInteger:(NSInteger)value forKey:(NSString *)key {
[self setDefault:@(value) forKey:key];
}
+ (void)setFloat:(CGFloat)value forKey:(NSString *)key {
[self setDefault:@(value) forKey:key];
}
+ (void)setDefaultsForDictionary:(NSDictionary *)newValues {
[[self sharedDefaults] setDefaultsWithDictionaryOnMainThread:newValues];
}
#pragma mark - Internal Methods
- (NSDictionary *)readFromFile {
NSDictionary * storedDefaults = nil;
if (self.defaultsURL) {
storedDefaults = [NSDictionary dictionaryWithContentsOfURL:self.defaultsURL];
}
return storedDefaults;
}
- (void)updateFromFileEvent {
// Read the file using our queue
MCC_PREFIXED_NAME(Defaults) * blockSelf = self;
NSDictionary __block * fileDefaults = nil;
[self.prefsAccessQueue addOperations:@[[NSBlockOperation blockOperationWithBlock:^{
fileDefaults = [blockSelf readFromFile];
}]] waitUntilFinished:YES];
// Then set the value using the main queue for the KVO stuff
NSDictionary * currentDefaults = [self.defaultDictionary copy];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSMutableArray * changedKeys = [NSMutableArray array];
NSSet * allKeySet = [[NSSet setWithArray:[fileDefaults allKeys]] setByAddingObjectsFromArray:[currentDefaults allKeys]];
for (id key in allKeySet) {
id value = [fileDefaults objectForKey:key];
if (value == nil) {
[self willChangeValueForKey:key];
[changedKeys addObject:key];
}
else if (![[currentDefaults objectForKey:key] isEqualTo:value]) {
[self willChangeValueForKey:key];
[changedKeys addObject:key];
}
}
self.defaultDictionary = fileDefaults;
[self writeToFile];
for (id key in changedKeys){
[self didChangeValueForKey:key];
}
}];
}
- (void)writeToFile {
if (self.defaultsURL && self.defaultDictionary) {
BOOL wantsBackups = self.delegateWantsBackups;
id<MCC_PREFIXED_NAME(DefaultsDelegate)> theDelegate = self.delegate;
NSURL * theURL = self.defaultsURL;
NSDictionary * theDict = self.defaultDictionary;
MCC_PREFIXED_NAME(FileEventQueue) * eventQueue = self.fileEventQueue;
[self.prefsAccessQueue addOperationWithBlock:^{
if (wantsBackups) {
[theDelegate backupCurrentDefaultsBeforeWriteAtURL:theURL];
}
// Remove any file event notification to not get it from ourselves
[eventQueue removePath:theURL.path];
[theDict writeToURL:theURL atomically:YES];
[eventQueue addAtomicPath:theURL.path withBlock:self.prefsChangeBlock notifyingAbout:PREF_FILE_NOTIFICATIONS];
}];
}
}
- (void)removeDefaultForKeyOnMainThread:(NSString*)key {
if (![NSThread isMainThread]){
[self performSelectorOnMainThread:_cmd withObject:key waitUntilDone:NO];
return;
}
NSMutableDictionary * plugInDefaults = [self.defaultDictionary mutableCopy];
MCC_AUTORELEASE(plugInDefaults);
if (!plugInDefaults) {
NSLog(@"Defaults is empty -- this should not happen");
// do not register these defaults -- just return.
return;
}
if (key && [plugInDefaults objectForKey:key]) {
[self willChangeValueForKey:key];
[plugInDefaults removeObjectForKey:key];
[self didChangeValueForKey:key];
}
else {
return;
}
self.defaultDictionary = [NSDictionary dictionaryWithDictionary:plugInDefaults];
[self writeToFile];
}
- (void)setDefaultsWithDictionaryOnMainThread:(NSDictionary *)dictionary {
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:_cmd withObject:dictionary waitUntilDone:NO];
return;
}
NSMutableDictionary * plugInDefaults = [self.defaultDictionary mutableCopy];
MCC_AUTORELEASE(plugInDefaults);
if (!plugInDefaults) {
NSLog(@"Defaults is empty -- this should not happen");
// do not register these defaults -- just return.
return;
}
NSMutableArray * changedKeys = [NSMutableArray array];
for (id key in [dictionary allKeys]) {
id value = [dictionary objectForKey:key];
if (value && key) {
if (![[plugInDefaults objectForKey:key] isEqualTo:value]) {
[self willChangeValueForKey:key];
[plugInDefaults setObject:value forKey:key];
[changedKeys addObject:key];
}
}
}
// Don't bother if nothing is different
if ([changedKeys count] == 0) {
return;
}
self.defaultDictionary = plugInDefaults;
[self writeToFile];
for (id key in changedKeys){
[self didChangeValueForKey:key];
}
}
- (NSDictionary *)_defaultsForKeys:(NSArray *)keys {
NSMutableDictionary MCC_WEAK_BLOCK * result = [NSMutableDictionary dictionaryWithCapacity:[keys count]];
NSDictionary * blockDefaults = self.defaultDictionary;
NSOperation * theReadBlock = [NSBlockOperation blockOperationWithBlock:^{
for (id aKey in keys){
id value = [blockDefaults objectForKey:aKey];
if (value) {
[result setValue:value forKey:aKey];
}
}
}];
// Throw on our queue and wait for the result
[self.prefsAccessQueue addOperations:@[theReadBlock] waitUntilFinished:YES];
return result;
}
- (id)_defaultForKey:(NSString *)key {
id __block result = nil;
NSDictionary * blockDefaults = self.defaultDictionary;
NSOperation * theReadBlock = [NSBlockOperation blockOperationWithBlock:^{
result = [blockDefaults objectForKey:key];
}];
// Throw on our queue and wait for the result
[self.prefsAccessQueue addOperations:@[theReadBlock] waitUntilFinished:YES];
return result;
}
- (id)_launchDefaultForKey:(NSString *)key {
return [[self launchDefaults] objectForKey:key];
}
- (NSDictionary *)launchDefaults {
static NSDictionary * launchArgs = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
launchArgs = [[NSUserDefaults standardUserDefaults] volatileDomainForName:NSArgumentDomain];
});
return launchArgs;
}
#pragma mark - Class Management
+ (instancetype)sharedDefaults {
return [self makeSharedDefaultsWithDelegate:nil];
}
+ (instancetype)makeSharedDefaultsWithDelegate:(id<MCC_PREFIXED_NAME(DefaultsDelegate)>)aDelegate {
static MCC_PREFIXED_NAME(Defaults) * theDefaults = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
theDefaults = [[self alloc] initWithDelegate:aDelegate];
MCC_RETAIN(theDefaults);
});
return theDefaults;
}
@end