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;

@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;


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

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



Joel Bernstein said...

Without question, categories are my favorite part of Objective C

SEO Services Consultants said...

Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming. Thanks again and good luck! Web Design Company

Martin said...

Is there a difference or advantage of using "[fh truncateFileAtOffset:[fh seekToEndOfFile]]" instead of simply "[fh seekToEndOfFile]"?