如何在OS X上查看文件更改?

zou*_*oul 4 macos objective-c grand-central-dispatch

我希望收到有关写入给定文件的通知 - 无需轮询,无需从文件中读取,也无需监视父目录并查看文件修改时间戳.我怎么做?

zou*_*oul 8

我找不到一个简单的例子,所以我正在贡献我想出的东西供将来参考:

@interface FileWatch ()
@property(assign) dispatch_source_t source;
@end

@implementation FileWatch
@synthesize source;

- (id) initWithPath: (NSString*) path targetQueue: (dispatch_queue_t) queue block: (dispatch_block_t) handler
{
    self = [super init];

    int descriptor = open([path fileSystemRepresentation], O_EVTONLY);
    if (descriptor < 0) {
        return nil;
    }

    [self setSource:dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, descriptor, DISPATCH_VNODE_WRITE, queue)];
    dispatch_source_set_event_handler(source, handler);
    dispatch_source_set_cancel_handler(source, ^{
        close(descriptor);
    });

    dispatch_resume(source);
    return self;
}

- (void) dealloc
{
    if (source) {
        dispatch_source_cancel(source);
        dispatch_release(source);
        source = NULL;
    }
}

@end
Run Code Online (Sandbox Code Playgroud)