Clean up after paths are unwatched. Add [PathWatcher unwatchAll]

This commit is contained in:
Corey Johnson & Nathan Sobo
2012-04-26 09:46:14 -07:00
parent 5156a37471
commit 6de031c41e
2 changed files with 28 additions and 2 deletions

View File

@@ -10,5 +10,6 @@ typedef void (^WatchCallback)(NSArray *);
+ (NSString *)watchPath:(NSString *)path callback:(WatchCallback)callback;
+ (void)unwatchPath:(NSString *)path callbackId:(NSString *)callbackId;
+ (void)unwatchAll;
@end

View File

@@ -10,6 +10,7 @@
- (NSString *)watchPath:(NSString *)path callback:(WatchCallback)callback;
- (void)watchFileDescriptor:(int)fd;
- (void)unwatchPath:(NSString *)path callbackId:(NSString *)callbackId;
- (void)unwatchAll;
@end
@implementation PathWatcher
@@ -28,6 +29,10 @@
return [[self instance] unwatchPath:path callbackId:callbackId];
}
+ (void)unwatchAll {
return [[self instance] unwatchAll];
}
- (void)dealloc {
close(_kq);
for (NSNumber *fdNumber in [_callbacksByFileDescriptor allKeys]) {
@@ -81,16 +86,36 @@
- (void)unwatchPath:(NSString *)path callbackId:(NSString *)callbackId {
@synchronized(self) {
NSNumber *fdNumber = [_fileDescriptorsByPath objectForKey:path];
NSNumber *fdNumber = [_fileDescriptorsByPath objectForKey:path];
if (!fdNumber) return;
NSMutableDictionary *callbacks = [_callbacksByFileDescriptor objectForKey:fdNumber];
if (!callbacks) return;
[callbacks removeObjectForKey:callbackId];
if (callbackId) {
[callbacks removeObjectForKey:callbackId];
}
else {
[callbacks removeAllObjects];
}
if (callbacks.count == 0) {
close([fdNumber intValue]);
[_fileDescriptorsByPath removeObjectForKey:path];
[_callbacksByFileDescriptor removeObjectForKey:fdNumber];
}
}
}
- (void)unwatchAll {
@synchronized(self) {
NSArray *paths = [_fileDescriptorsByPath allKeys];
for (NSString *path in paths) {
[self unwatchPath:path callbackId:nil];
}
}
}
- (void)watchFileDescriptor:(int)fd {
struct timespec timeout = { 0, 0 };
struct kevent event;