美文网首页
DISPATCH_SOURCE_TYPE_WRITE

DISPATCH_SOURCE_TYPE_WRITE

作者: iOS的Developer | 来源:发表于2017-05-31 12:00 被阅读0次
#import "ViewController.h"

int n = 0;

@interface ViewController ()

@end

@implementation ViewController

#pragma mark - Writing Data to a Descriptor

dispatch_source_t WriteDataToFile(const char* fileName) {
    int fd = open(fileName, O_WRONLY | O_CREAT | O_TRUNC, (S_IRUSR | S_IWUSR | S_ISUID | S_ISGID));
    
    if (fd == -1)
        return NULL;
    
    fcntl(fd, F_SETFL);// Block during the write.
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t writeSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, fd, 0, queue);
    
    if (!writeSource) {
        close(fd);
        return NULL;
    }
    
    dispatch_source_set_event_handler(writeSource, ^{
        size_t bufferSize = MyGetDataSize();
        void* buffer = malloc(bufferSize);
        
        size_t actual = MyGetData(buffer, bufferSize);
        
        write(fd, buffer, actual);
        
        free(buffer);
        
        if(n >= 1000)
        {
            dispatch_source_cancel(writeSource);
        }
        
        // Cancel and release the dispatch source when done.
        //dispatch_source_cancel(writeSource);
    });
    
    dispatch_source_set_cancel_handler(writeSource, ^{
        close(fd);
    });
    
    dispatch_resume(writeSource);
    
    return writeSource;
}

size_t MyGetDataSize() {
    //replace code
    n++;
    return 100;
}

size_t MyGetData(void* buffer, size_t size) {
    //replace code
    memcpy(buffer, "abcdefghijklmnopqrstuvwxyz", 26);
    return 26;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    WriteDataToFile("/Users/weiyanwu/Desktop/ZOWrite.txt");
}


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


@end

网友评论

      本文标题:DISPATCH_SOURCE_TYPE_WRITE

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