forked from gnachman/iTerm2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TSVParser.m
79 lines (64 loc) · 1.63 KB
/
TSVParser.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
//
// TSVParser.m
// iTerm
//
// Created by George Nachman on 11/27/11.
//
#import "TSVParser.h"
@implementation TSVDocument
@synthesize columns = columns_;
@synthesize records = records_;
- (id)init
{
self = [super init];
if (self) {
records_ = [[NSMutableArray alloc] init];
}
return self;
}
- (void)dealloc
{
[columns_ release];
[records_ release];
[map_ release];
[super dealloc];
}
- (NSString *)valueInRecord:(NSArray *)record forField:(NSString *)fieldName
{
if (!map_) {
map_ = [[NSMutableDictionary dictionary] retain];
for (int i = 0; i < self.columns.count; i++) {
[map_ setObject:[NSNumber numberWithInt:i]
forKey:[self.columns objectAtIndex:i]];
}
}
NSNumber *n = [map_ objectForKey:fieldName];
int i = [n intValue];
if (n && i < [record count]) {
return [record objectAtIndex:i];
}
return nil;
}
@end
@implementation TSVParser
+ (TSVDocument *)documentFromString:(NSString *)string withFields:(NSArray *)fields
{
NSArray *lines = [string componentsSeparatedByString:@"\n"];
if ([lines count] == 0) {
return nil;
}
TSVDocument *doc = [[[TSVDocument alloc] init] autorelease];
doc.columns = [[fields copy] autorelease];
for (int i = 0; i < lines.count; i++) {
NSString *row = [lines objectAtIndex:i];
[doc.records addObject:[row componentsSeparatedByString:@"\t"]];
}
return doc;
}
@end
@implementation NSString (TSV)
- (TSVDocument *)tsvDocumentWithFields:(NSArray *)fields
{
return [TSVParser documentFromString:self withFields:fields];
}
@end