-
Notifications
You must be signed in to change notification settings - Fork 1
/
TLSavedState.m
110 lines (83 loc) · 2.5 KB
/
TLSavedState.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
//
// TLSavedState.m
// TLCommon
//
// Created by Joshua Bleecher Snyder on 9/7/09.
//
#import "TLSavedState.h"
#import "NSFileManager_TLCommon.h"
@class TLSavedStateNotificationRecipient;
static NSMutableDictionary *state = nil;
static TLSavedStateNotificationRecipient *notificationRecipient = nil;
#pragma mark -
@interface TLSavedState ()
+ (NSString *)stateSavePath;
+ (void)saveState;
@end
#pragma mark -
@interface TLSavedStateNotificationRecipient : NSObject
- (void)didReceiveNotification:(NSNotification *)notification;
@end
#pragma mark -
@implementation TLSavedStateNotificationRecipient
- (id)init {
if(self = [super init]) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(didReceiveNotification:)
name:UIApplicationWillTerminateNotification
object:[UIApplication sharedApplication]];
}
return self;
}
- (void)didReceiveNotification:(NSNotification *)notification {
[TLSavedState saveState];
}
@end
#pragma mark -
@implementation TLSavedState
+ (void)initialize {
if([self class] == [TLSavedState class]) {
if(!state) {
state = [NSMutableDictionary dictionaryWithContentsOfFile:[[self class] stateSavePath]];
if(!state) {
state = [NSMutableDictionary dictionary];
}
[state retain];
if(!notificationRecipient) {
notificationRecipient = [[TLSavedStateNotificationRecipient alloc] init];
}
}
}
}
+ (id)valueForKey:(NSString *)key {
id value = [state objectForKey:key];
if(value == [NSNull null]) {
value = nil;
}
return value;
}
+ (void)setValue:(id)value forKey:(NSString *)key {
if(!value) {
value = [NSNull null];
}
[state setObject:value forKey:key];
}
+ (BOOL)firstTimeForEvent:(NSString *)keyRepresentingEvent {
NSString *mangledKey = [@"TLSavedStateInternal_FirstTime_" stringByAppendingString:keyRepresentingEvent];
BOOL firstTime = ![[self valueForKey:mangledKey] boolValue];
if(firstTime) {
[self setValue:[NSNumber numberWithBool:YES] forKey:mangledKey];
}
return firstTime;
}
+ (NSString *)stateSavePath {
NSString *savePath = [[NSFileManager applicationDocumentsDirectory] stringByAppendingPathComponent:@"tl_saved_state"];
return savePath;
}
- (NSDictionary *)dictionaryRepresentation {
return [[state copy] autorelease];
}
+ (void)saveState {
[state writeToFile:[[self class] stateSavePath] atomically:YES];
}
@end