美文网首页
DISPATCH_SOURCE_TYPE_READ

DISPATCH_SOURCE_TYPE_READ

作者: iOS的Developer | 来源:发表于2017-05-31 09:37 被阅读0次

#import "ViewController.h"

@interface ViewController ()
{
    dispatch_source_t _readSource;
}

@end

@implementation ViewController


-(BOOL)myProcesFileData:(char *)buffer actutalSize:(size_t)actutalSize fd:(int)fd
{

    NSString *str = [[NSString alloc] initWithBytes:buffer length:actutalSize encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);
    NSLog(@"%li", actutalSize);
 
    if(actutalSize < 260)
    {
        return YES;
    }
    else
    {
        return NO;
    }
    
}


void cancelHandler(void *context)
{
    int fd = (int)dispatch_source_get_handle((__bridge dispatch_source_t _Nonnull)(context));
    close(fd);
}


-(dispatch_source_t)createFileDispatchSource:(const char *)fileName
{
    //1:打开文件,获取文件描述符(open成功则返回文件描述符,否则返回-1)
    int fd = open(fileName, O_RDWR);
    if (fd == -1)
    {
        return NULL;
    }
    
    //2:设置文件操作为非堵塞模式(也可以在pen函数中设置:open(fileName, O_RDONLY|O_NONBLOCK))
    fcntl(fd, F_SETFL, O_NONBLOCK);
    
    //3:创建派发源
    dispatch_queue_t queue = dispatch_queue_create("同一文件操作都在串行队列中", DISPATCH_QUEUE_SERIAL);
    
    _readSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, fd, 0, queue);
    
    if (_readSource == NULL)
    {
        close(fd);
        return NULL;
    }
    
    //4:设置”文件可读“事件响应处理器
    dispatch_source_set_event_handler(_readSource, ^{
        
        size_t estimated = 260;
        char *buffer = (char*)malloc(estimated);
        if(buffer)
        {
            size_t actualSize = read(fd, buffer, estimated);
            BOOL done = [self myProcesFileData:buffer actutalSize:actualSize fd:fd];

            free(buffer);
            
            if (done)
            {
                dispatch_source_cancel(_readSource);
            }
        }
        
    });
    
 
    //使用函数处理器
    dispatch_set_context(_readSource, (__bridge void *)_readSource);
    dispatch_source_set_cancel_handler_f(_readSource, cancelHandler);
    
    //6:启动事件源
    dispatch_resume(_readSource);
    
    return _readSource;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self createFileDispatchSource:"/Users/weiyanwu/Desktop/ZORead.txt"];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

网友评论

      本文标题:DISPATCH_SOURCE_TYPE_READ

      本文链接:https://www.haomeiwen.com/subject/vrmdfxtx.html