Created
October 4, 2010 07:20
-
-
Save stevestreza/609343 to your computer and use it in GitHub Desktop.
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
// | |
// NSFileManager+BKExtensions.h | |
// BlocksKit | |
// | |
// Created by Steve Streza on 10/3/10. | |
// Copyright 2010 Steve Streza. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
@interface NSFileManager (BKExtensions) | |
-(void)BK_getContentsAtPath:(NSString *)path handler:(void (^)(NSData *data, NSError *error))handler; | |
@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
// | |
// NSFileManager+BKExtensions.m | |
// BlocksKit | |
// | |
// Created by Steve Streza on 10/3/10. | |
// Copyright 2010 Steve Streza. All rights reserved. | |
// | |
#import "NSFileManager+BKExtensions.h" | |
#import <dispatch/dispatch.h> | |
#define DISPATCH_GET_DEFAULT_GLOBAL_QUEUE() dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) | |
@implementation NSFileManager (BKExtensions) | |
-(void)BK_getContentsAtPath:(NSString *)path handler:(void (^)(NSData *, NSError *))handler{ | |
dispatch_queue_t queue = DISPATCH_GET_DEFAULT_GLOBAL_QUEUE(); | |
dispatch_async(queue, ^{ | |
NSFileHandle *fh = [[NSFileHandle fileHandleForReadingAtPath:path] retain]; | |
NSError *error = nil; | |
NSMutableData *data = [[NSMutableData data] retain]; | |
// create a GCD source using the file descriptor, which will respond whenever the descriptor fires | |
dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, [fh fileDescriptor], 0, queue); | |
dispatch_source_set_event_handler(source, ^{ | |
BOOL eof = NO; | |
// if we get less than this much, we hit end of file, so we can file the callback | |
NSUInteger max = 65536; | |
NSData *newData = [fh readDataOfLength:max]; | |
if(!newData || newData.length < max){ | |
eof = YES; | |
} | |
[data appendData:newData]; | |
if(eof){ | |
dispatch_async(dispatch_get_main_queue(), ^{ | |
handler(data, error); | |
[data release]; | |
}); | |
dispatch_source_cancel(source); | |
[fh release]; | |
} | |
}); | |
dispatch_resume(source); | |
}); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment