Domanda

I am new to Cocoa Application development. I want my application to be notified when any file under a given directory is modified(folder watcher). Modified means deleted, added, content of file is changed. I tried using FSEvents also with using NSWorkspace's notification center or delegate messages as in UKKQueue at http://www.zathras.de/angelweb/sourcecode.htm#UKKQueue. My application got notification when any file under directory is modified. But the problem is that its not giving name or path of specific file which is modified. It gives path of directory but not path of specific file.

Any idea how can I watch folder for modification in specific file??

È stato utile?

Soluzione

You have to write code to keep track of the contents of the folder and then whenever you receive an FSEvent notification that the folder contents have changed, you need to compare your stored information about the folder contents with the actual, current contents.

This could be something as simple as a mutable array ivar named something like folderContents, which contains a set of file attributes dictionaries. You could use the dictionary returned from the -attributesOfItemAtPath:error: method of NSFileManager or a subset of it.

All you'd need to do when you receive a folder notification is iterate through the stored dictionaries and check to see whether any files have been added, removed or modified. The NSFileManager attributes dictionary contains all the info you need to do this.

You'd then need to update your stored information about the folder with the updated information.

Altri suggerimenti

NSMetadataQuery works well for watching folders:

- (void)setupWatchedFolder {
    NSString *watchedFolder = @"/path/to/foo";

    NSMetadataQuery *query = [[NSMetadataQuery alloc] init];
    [query setSearchScopes:@[watchedFolder]];
    [query setPredicate:[NSPredicate predicateWithFormat:@"%K LIKE '*.*'", NSMetadataItemFSNameKey]];

    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self selector:@selector(queryFoundStuff:) name:NSMetadataQueryDidFinishGatheringNotification object:query];
    [nc addObserver:self selector:@selector(queryFoundStuff:) name:NSMetadataQueryDidUpdateNotification object:query];

    [query startQuery];
}

- (void)queryFoundStuff:(NSNotification *)notification {

    NSMetadataQuery *query = self.metadataQuery;
    [query disableUpdates];

    NSMutableArray *results = [NSMutableArray arrayWithCapacity:self.metadataQuery.resultCount];

    for (NSUInteger i=0; i<self.metadataQuery.resultCount; i++) {
        [results addObject:[[self.metadataQuery resultAtIndex:i] valueForAttribute:NSMetadataItemPathKey]];
    }

    // do something with you search results
    // self.results = results;

    [query enableUpdates];
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top