我做了以下操作,以便能够区分正在监视的文件夹内的文件的不同操作FSEvent
(添加文件、重命名文件、删除文件和修改文件)。
我创建了一个File
具有以下属性的对象(您可以通过调用获得任意数量的对象attributesOfItemAtPath:error:
):
@property (strong) NSString *name;
@property (strong) NSString *type;
@property (strong) NSDate *creationDate;
@property (strong) NSDate *modificationDate;
@property (strong) NSString *hash;
@property (strong) NSString *path;
可以通过以下方式填充NSMutableArray
File 对象:
NSMutableArray *files = [[NSMutableArray alloc] init];
NSString *dirPath = //directory you are watching
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *theFiles = [fileManager contentsOfDirectoryAtURL:[NSURL fileURLWithPath:dirPath]
includingPropertiesForKeys:[NSArray arrayWithObject:NSURLNameKey]
options:NSDirectoryEnumerationSkipsHiddenFiles
error:nil];
NSArray* fileNames = [theFiles valueForKeyPath:@"lastPathComponent"];
if ( [fileNames count] > 0 ) {
for (NSInteger i=0; i<[fileNames count]; i=i+1) {
NSString *currentPath = [dirPath stringByAppendingString:[fileNames objectAtIndex:i]];
NSError *error;
NSDictionary *fileInfo = [fileManager attributesOfItemAtPath:currentPath error:&error];
File *currentFile = [[File alloc] initWithName:[fileNames objectAtIndex:i]
withType:fileInfo.fileType
withPath:currentPath
withHash: //get file hash
withCreationDate:fileInfo.fileCreationDate
andWithModificationDate:fileInfo.fileModificationDate];
[files addObject:currentFile];
}
如果目录包含子文件夹,则为每个子文件夹迭代此过程就足够了,返回 File 对象数组。
要了解执行了什么操作,现在只需面对NSMutableArray *oldSnap
在NSMutableArray *newSnap
. FSEvent
首先,有必要将文件与文件放在oldSnap
一起newSnap
,然后反之亦然。
如果 inoldSnap
中缺少给定名称的文件newSnap
,则表示该文件已被删除或重命名。如果在 中存在具有相同哈希newSnap
的文件,则该文件已被重命名;否则它已从文件夹中删除。
完成比较,如果 中的文件与 中的同名文件newSnap
不同,则该文件已被修改。如果 newSnap 中有一个文件在fileModificationDate
oldSnap
oldSnap
,则该文件是新添加的。
我还没有想出一个关于重命名和修改文件的解决方案。希望这个答案可以帮助其他人!