ライブラリにしようかと思ったら単純なフォーマットだったのでスニペットにした。
main.m
- (NSArray *)objectsWithString:(NSString *)string
{
NSMutableArray* result = [NSMutableArray array];
[string enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) {
NSMutableDictionary* record = [NSMutableDictionary dictionary];
for (NSString* block in [line componentsSeparatedByString:@"\t"]) {
NSRange range = [block rangeOfString:@":"];
if(range.location != NSNotFound){
[record setObject:[block substringFromIndex:range.location+range.length] forKey:[block substringToIndex:range.location]];
}
}
if(record.allKeys.count > 0){
[result addObject:record];
}
}];
return result;
}
テストもあるでよ
Tests.m
- (void)testResultCountObjCImpl
{
NSArray* objects = [self objectsWithString:[self stringSourceFixture]];
XCTAssertEqual(objects.count, (NSUInteger)3);
}
- (void)testResultKeysCountObjCImpl
{
NSDictionary* record = [[self objectsWithString:[self stringSourceFixture]] lastObject];
XCTAssertEqual(record.allKeys.count, [[self labelsFixture] count]);
}
- (void)testResultObjCImpl
{
NSArray* objects = [self objectsWithString:[self stringSourceFixture]];
NSDictionary* record = [objects objectAtIndex:0];
[[self labelsFixture] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
BOOL ret = [[record allKeys] containsObject:obj];
XCTAssertTrue(ret);
}];
}
- (void)testEmptyString
{
NSArray* objects = [self objectsWithString:@""];
XCTAssertEqual(objects.count, (NSUInteger)0);
}
- (void)testInvalidString
{
NSArray* objects = [self objectsWithString:@"abc-?!bcc"];
XCTAssertEqual(objects.count, (NSUInteger)0);
}
# pragma mark - Helpers
- (NSString *)stringSourceFixture
{
//http://d.hatena.ne.jp/naoya/20130209/1360381374
return @""
"host:127.0.0.1\tident:-\tuser:frank\ttime:[12/Oct/2000:13:55:36 -0700]\treq:GET /apache_pb.gif HTTP/1.0\tstatus:200\tsize:2326\treferer:http://www.example.com/start.html\tua:Mozilla/4.08 [en] (Win98; I ;Nav)\n"
"host:127.0.0.1\tident:-\tuser:frank\ttime:[11/Oct/2000:13:55:36 -0700]\treq:GET /apache_pb.gif HTTP/1.0\tstatus:200\tsize:2326\treferer:http://www.example.com/start.html\tua:Mozilla/4.08 [en] (Win98; I ;Nav)\n"
"host:127.0.0.1\tident:-\tuser:frank\ttime:[10/Oct/2000:13:55:36 -0700]\treq:GET /apache_pb.gif HTTP/1.0\tstatus:200\tsize:2326\treferer:http://www.example.com/start.html\tua:Mozilla/4.08 [en] (Win98; I ;Nav)\n";
}
- (NSArray *)labelsFixture
{
return @[@"host", @"referer",@"ua", @"user", @"ident", @"time", @"req", @"status", @"size"];
}
- (NSArray *)valuesFixture
{
return @[@"127.0.0.1", @"http://www.example.com/start.html", @"Mozilla/4.08 [en] (Win98; I ;Nav)", @"frank", @"-", @"[12/Oct/2000:13:55:36 -0700]", @"GET /apache_pb.gif HTTP/1.0", @"200", @"2326"];
}