在fsevents中更改pathsToWatch

时间:2011-08-17 16:05:32

标签: cocoa fsevents

我已经使用fsevents建立了一个观察者机制。它的要点是每次在文件夹X中创建文件时,我都希望运行一个函数。它现在运行正常,但我需要能够改变它正在观看的路径。这是设置代码:

void *appPointer = (void *)self;
NSString *myPath = [[[NSUserDefaultsController sharedUserDefaultsController] defaults] stringForKey:@"FolderPath"];
NSArray *pathsToWatch = [NSArray arrayWithObject:myPath];
FSEventStreamContext context = {0, appPointer, NULL, NULL, NULL};
NSTimeInterval latency = 1.0;
stream = FSEventStreamCreate(NULL, 
                             &fsevents_callback, 
                             &context, 
                             (CFArrayRef) pathsToWatch, 
                             [lastEventId unsignedLongLongValue], 
                             (CFAbsoluteTime) latency, 
                             kFSEventStreamCreateFlagUseCFTypes
                             );
FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
FSEventStreamStart(stream);

我首先尝试停止FSEventStream,然后再次启动它,但在再次调用exc_bad_access时我得到FSEventStreamCreate

还尝试动态调整pathsToWatch数组,但这也导致了错误的访问错误。

有更好的方法吗?

1 个答案:

答案 0 :(得分:3)

问题是事件流仍在安排中;阻止它是不够的。我是这样做的:

- (void)initializeEventStream {
    void *appPointer = (void *)self;
    FSEventStreamContext context = {0, appPointer, NULL, NULL, NULL};
    NSTimeInterval latency = 1.0;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray *pathsToWatch = [NSArray arrayWithObject:[defaults stringForKey:@"SomeKey"]];

    stream = FSEventStreamCreate(NULL, 
                                 &fsevents_callback, 
                                 &context, 
                                 (CFArrayRef) pathsToWatch, 
                                 [lastEventId unsignedLongLongValue], 
                                 (CFAbsoluteTime) latency, 
                                 kFSEventStreamCreateFlagUseCFTypes
                                 );
    FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
    FSEventStreamStart(stream);
}

- (void)stopEventStream {
    FSEventStreamStop(stream);
    FSEventStreamUnscheduleFromRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
}

基本上与我在问题中列出的相同,但也有FSEventStreamUnscheduleFromRunLoop