FSEvents-检测文件夹上的事件类型

时间:2014-02-28 07:31:59

标签: objective-c macos cocoa

关于如何检测回调方法中文件夹中引发的文件夹事件类型(FSEvent)的任何想法(以下代码中的gotEvent方法)?例如:文件重命名,文件创建?我想只使用File Renamed,File Created进行一些操作。想忽略其他事件。

我有以下实施 -

- (FSEventStreamRef) eventStreamForFileAtPath: (NSString *) fileInputPath  {

    if (![[NSFileManager defaultManager] fileExistsAtPath:fileInputPath]) {
        @throw [NSException exceptionWithName:@"FileNotFoundException"
                                       reason:@"There is not file at path specified in fileInputPath"
                                     userInfo:nil];
    }

    NSString *fileInputDir = [fileInputPath stringByDeletingLastPathComponent];

    NSArray *pathsToWatch = [NSArray arrayWithObjects:fileInputDir, nil];

    void *appPointer = (__bridge void *)self;

    FSEventStreamContext context = {0, appPointer, NULL, NULL, NULL};

    NSTimeInterval latency = 3.0;

    FSEventStreamRef stream = FSEventStreamCreate(NULL,
                                                  &gotEvent,
                                                  &context,
                                                  (__bridge CFArrayRef) pathsToWatch,
                                                  kFSEventStreamEventIdSinceNow,
                                                  (CFAbsoluteTime) latency,
                                                  kFSEventStreamCreateFlagUseCFTypes
                                                  );

    FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
    FSEventStreamStart(stream);

    return stream;

}

static void gotEvent(ConstFSEventStreamRef stream,
                     void *clientCallBackInfo,
                     size_t numEvents,
                     void *eventPathsVoidPointer,
                     const FSEventStreamEventFlags eventFlags[],
                     const FSEventStreamEventId eventIds[]
                     ) {

    NSLog(@"File Changed!");
}

1 个答案:

答案 0 :(得分:1)

根据Apple FSEventStreamEventFlags,{{1}}应该表明发生了什么。

  

kFSEventStreamEventFlagItemCreated = 0x00000100,
  kFSEventStreamEventFlagItemRemoved = 0x00000200,
  kFSEventStreamEventFlagItemRenamed = 0x00000800,
  kFSEventStreamEventFlagItemModified = 0x00001000,

评估设置的标志应该完全符合您的要求。