How to detect directory changes using GCD

From this post I’ll write some Objective-C code here periodically. Today we’re talking about detecting directory changes. There are several different ways to do that, for example, kqueue or GCD. Detection of directory changes used in my app, Filegrid, version 1.2, that is not yet released at the moment.

Grand Central Dispatch (GCD) is a technology developed by Apple Inc. to optimize application support for systems with multi-core processors and other symmetric multiprocessing systems. It is an implementation of task parallelism based on the thread pool pattern. It was first released with Mac OS X 10.6, and is also available with iOS 4 and above.

So note that GCD is available only in OS X 10.6 and above, and iOS4 and above. In earlier versions of this amazing software I’d recommend using kqueue.

We don’t need to create a custom class, just write that somewhere you want. The code may look like that:

int fildes = open("/path/to/directory", O_RDONLY);

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_source_set_event_handler(source, ^{
// ... handle changes

dispatch_source_set_cancel_handler(source, ^{
// ... handle cancel

dispatch_resume(source); // Start monitoring

// And sometime later
dispatch_source_cancel(source); // Stop monitoring

Here in the code you see a bunch of vnodes. Vnodes – is basically a flags of how do you watching a directory. For example, our “watcher” will react on deleting files from that directory, if you write DISPATCH_VNODE_DELETE. The same thing with DISPATCH_VNODE_RENAME (a file was renamed), DISPATCH_VNODE_ATTRIB (a file metadata was changed) and so on. The full list of vnodes is available here.

You may have a problem with the first line of the code above, like me: Use of undeclared identifier ‘O_RDONLY’. If that happened, just do this:



The problem will go away and this code will work properly.

Note that open() function uses the C string. The code below shows what you can write instead of “path/to/directory” (Documents directory as example). We’re converting our NSString to a C string.

[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] cStringUsingEncoding:NSASCIIStringEncoding]

One thought on “How to detect directory changes using GCD”

Leave a Reply.