Wednesday, August 18, 2010

The Funny Thing About Old Code…

The funny thing about old code, and most new code, is that there's usually room for improvement. Shortly after posting NSString appendToFile:usingEncoding:, I realized I could've kill two birds with one stone by adding a category method on NSData and then calling that method from the NSString category method. That way I'd get the functionality on both classes without repeating logic.

Without further ado:

#import <Foundation/Foundation.h>

@interface NSData(MCFileAppend)
- (BOOL)appendToFile:(NSString *)path;
@end

@implementation NSData(MCFileAppend)
- (BOOL)appendToFile:(NSString *)path
{
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:path];
if (fh == nil)
return [self writeToFile:path atomically:YES];

[fh truncateFileAtOffset:[fh seekToEndOfFile]];

[fh writeData:self];
[fh closeFile];
return YES;
}

@end

#pragma mark -
@interface NSString(MCFileAppend)
- (BOOL)appendToFile:(NSString *)path usingEncoding:(NSStringEncoding)encoding;
@end

@implementation NSString(MCFileAppend)
- (BOOL)appendToFile:(NSString *)path usingEncoding:(NSStringEncoding)encoding
{
NSData *encoded = [self dataUsingEncoding:encoding];
return [encoded appendToFile:path];
}

@end

No comments:

Post a Comment