-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPSRNoteManager.m
More file actions
87 lines (68 loc) · 2.07 KB
/
PSRNoteManager.m
File metadata and controls
87 lines (68 loc) · 2.07 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
84
85
86
87
//
// PSRNoteManager.m
// SimpleNotes
//
// Created by Daniil Korotin on 24.04.14.
// Copyright (c) 2014 Daniil Korotin. All rights reserved.
//
#import "PSRNoteManager.h"
@implementation PSRNoteManager
+ (instancetype)sharedManager {
static dispatch_once_t token;
static id shared = nil;
dispatch_once(&token, ^{
shared = [[super alloc] init];
});
return shared;
}
- (id)init {
self = [super init];
if (self) {
_notes = [[NSMutableArray alloc] init];
}
return self;
}
- (NSString *)fileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *cachePath = [paths objectAtIndex:0];
BOOL isDir = NO;
NSError *error;
if (! [[NSFileManager defaultManager] fileExistsAtPath:cachePath isDirectory:&isDir] && isDir == NO) {
[[NSFileManager defaultManager] createDirectoryAtPath:cachePath withIntermediateDirectories:NO attributes:nil error:&error];
}
return [NSString stringWithFormat:@"%@/mynotes.data", cachePath];
}
- (void)loadFromFile {
NSData *frozenInfo = [NSData dataWithContentsOfFile: [self fileName]];
_notes = [NSKeyedUnarchiver unarchiveObjectWithData:frozenInfo];
if (!self.notes) {
_notes = [[NSMutableArray alloc] init];
}
}
-(void)saveToFile {
NSData *frozenInfo = [NSKeyedArchiver archivedDataWithRootObject:self.notes];
[frozenInfo writeToFile:[self fileName] atomically:NO];
}
- (PSRNote *)findNoteByDate:(NSDate *)date {
for (PSRNote *note in self.notes) {
if ([note.date isEqualToDate:date]) {
return note;
}
}
return nil;
}
-(void)addOrUpdateNote:(PSRNote *)note {
PSRNote *noteToUpdate = [self findNoteByDate:note.date];
if (noteToUpdate) {
noteToUpdate.text = note.text;
} else {
[_notes insertObject:note atIndex:0];
}
}
-(void)removeNote:(PSRNote *)note {
PSRNote *noteToDelete = [self findNoteByDate:note.date];
if (noteToDelete) {
[_notes removeObject:noteToDelete];
}
}
@end