Created
July 11, 2013 01:20
-
-
Save beccadax/5971746 to your computer and use it in GitHub Desktop.
Class to enumerate over the contents of a file handle line-by-line
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// TsLineEnumerator.h | |
// Typesetter | |
// | |
// Created by Brent Royal-Gordon on 2/3/12. | |
// Copyright (c) 2012 Architechies. All rights reserved. | |
// | |
@interface NSFileHandle (lineEnumerator) | |
- (NSEnumerator*)lineEnumerator; | |
@end | |
@interface TsLineEnumerator : NSEnumerator | |
- (id)initWithReadingFileHandle:(NSFileHandle*)fh; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// TsLineEnumerator.m | |
// Typesetter | |
// | |
// Created by Brent Royal-Gordon on 2/3/12. | |
// Copyright (c) 2012 Architechies. All rights reserved. | |
// | |
#import "TsLineEnumerator.h" | |
@implementation NSFileHandle (lineEnumerator) | |
- (NSEnumerator *)lineEnumerator { | |
return [[TsLineEnumerator alloc] initWithReadingFileHandle:self]; | |
} | |
@end | |
@interface TsLineEnumerator () | |
@property (strong) NSFileHandle * fileHandle; | |
@property (strong) NSMutableString * buffer; | |
@end | |
@implementation TsLineEnumerator | |
- (id)initWithReadingFileHandle:(NSFileHandle *)fh { | |
if((self = [super init])) { | |
self.fileHandle = fh; | |
self.buffer = [NSMutableString new]; | |
} | |
return self; | |
} | |
- (id)nextObject { | |
if(self.buffer == nil) { | |
return nil; | |
} | |
NSRange lineBreakRange = [self.buffer rangeOfString:@"\n"]; | |
if(lineBreakRange.location != NSNotFound) { | |
NSRange lineRange = NSMakeRange(0, lineBreakRange.location + lineBreakRange.length); | |
NSString * line = [self.buffer substringWithRange:lineRange]; | |
[self.buffer deleteCharactersInRange:lineRange]; | |
return line; | |
} | |
// We don't have a line... | |
NSData * data = [self.fileHandle availableData]; | |
if(data.length == 0) { | |
// End of file--we'll have to return the buffer as the last line. | |
NSString * line = self.buffer.copy; | |
self.buffer = nil; // mark it as EOF | |
return line; | |
} | |
// Append the data to the buffer... | |
[self.buffer appendString:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]]; | |
// ...and try it all again. | |
return [self nextObject]; | |
} | |
@synthesize fileHandle; | |
@synthesize buffer; | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment