开发者

Changing the pathsToWatch in fsevents

I've set up a watcher mechanism using fsevents. The gist of it is every time a file is created in folder X, I want a function to run. It's running fine now, but I need to be able to change the path it is watching. Here's the setup code:

void *appPointer = (void *)self;
NSString *my开发者_StackOverflow社区Path = [[[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);

I first tried just stopping the FSEventStream, then starting it up again, but I get an exc_bad_access when calling FSEventStreamCreate again.

Also tried adjusting the pathsToWatch array on the fly, but that also caused a bad access error too.

Is there a better way to do this?


The problem was that the event stream was still scheduled; stopping it wasn't enough. Here's how I did it:

- (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);
}

Basically the same thing as I listed in my question, but with FSEventStreamUnscheduleFromRunLoop too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜