-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathSSYLinearFileWriter.m
106 lines (85 loc) · 2.63 KB
/
SSYLinearFileWriter.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
#import "SSYLinearFileWriter.h"
// This is a singleton, but not a "true singletons", because
// I didn't bother to override
// +allocWithZone:
// -copyWithZone:
// -retain
// -retainCount
// -release
// -autorelease
static SSYLinearFileWriter* sharedFileWriter = nil ;
@interface SSYLinearFileWriter ()
@property (retain) NSFileHandle* fileHandle ;
@end
@implementation SSYLinearFileWriter
@synthesize fileHandle = m_fileHandle ;
+ (SSYLinearFileWriter*)sharedFileWriter {
@synchronized(self) {
if (!sharedFileWriter) {
sharedFileWriter = [[self alloc] init] ;
}
}
// No autorelease. This sticks around forever.
return sharedFileWriter ;
}
- (void)setPath:(NSString*)path {
NSFileManager* fileManager = [NSFileManager defaultManager];
NSString* parentPath = [path stringByDeletingLastPathComponent];
BOOL parentDirectoryIsDirectory = NO;
BOOL parentDirectoryExists = [fileManager fileExistsAtPath:parentPath
isDirectory:&parentDirectoryIsDirectory];
BOOL needsCreateDirectory = NO;
if (parentDirectoryExists) {
if (!parentDirectoryIsDirectory) {
[fileManager removeItemAtPath:parentPath
error:NULL];
needsCreateDirectory = YES;
}
} else {
needsCreateDirectory = YES;
}
if (needsCreateDirectory) {
[fileManager createDirectoryAtPath:parentPath
withIntermediateDirectories:YES
attributes:nil
error:NULL];
}
[fileManager createFileAtPath:path
contents:[NSData data]
attributes:nil] ;
NSFileHandle* fileHandle = [NSFileHandle fileHandleForWritingAtPath:path] ;
[self setFileHandle:fileHandle] ;
}
- (void)writeLine:(NSString*)line {
line = [line stringByAppendingString:@"\n"] ;
NSData* data = [line dataUsingEncoding:NSUTF8StringEncoding] ;
NSFileHandle* fileHandle = [self fileHandle] ;
if (fileHandle) {
[[self fileHandle] writeData:data] ;
}
else {
NSLog(@"Internal Error 810-1149 No fileHandle") ;
}
}
+ (void)setToPath:(NSString*)path {
if (sharedFileWriter) {
#if !__has_feature(objc_arc)
[sharedFileWriter release] ;
#endif
sharedFileWriter = nil ;
}
[[SSYLinearFileWriter sharedFileWriter] setPath:path] ;
}
+ (void)writeLine:(NSString*)line {
[[SSYLinearFileWriter sharedFileWriter] writeLine:line] ;
}
+ (void)close {
[[SSYLinearFileWriter sharedFileWriter] setFileHandle:nil] ;
}
#if !__has_feature(objc_arc)
- (void)dealloc {
[m_fileHandle release] ;
[super dealloc] ;
}
#endif
@end