NSMetadataQueryDidFinishGatheringNotification从来没有所谓
问题描述:
试图运行下面的代码:NSMetadataQueryDidFinishGatheringNotification从来没有所谓
#import <Foundation/Foundation.h>
@interface FileQuery : NSObject
@end
@interface FileQuery()
@property (nonatomic, strong) NSMetadataQuery *query;
@property (nonatomic, strong) NSMutableArray<NSURL *> *fileArray;
@end
@implementation FileQuery
-(void)stopQuery {
if (_query) {
NSLog(@"No longer watching iCloud dir...");
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSMetadataQueryDidFinishGatheringNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSMetadataQueryDidUpdateNotification object:nil];
[_query stopQuery];
_query = nil;
_fileArray = nil;
}
}
-(BOOL)startQuery:(NSString *)suffix {
[_query stopQuery];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(processFiles:)
name:NSMetadataQueryDidFinishGatheringNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(processFiles:)
name:NSMetadataQueryDidUpdateNotification
object:nil];
_query = [NSMetadataQuery new];
if (_query) {
NSLog(@"aa");
_fileArray = [NSMutableArray new];
[_query setSearchScopes:@[NSMetadataQueryLocalComputerScope]];
[_query setPredicate:[NSPredicate predicateWithFormat:@"%K BEGINSWITH %@",
NSMetadataItemFSNameKey, suffix]];
dispatch_async(dispatch_get_main_queue(), ^{
if ([_query startQuery]) {
[_query enableUpdates];
NSLog(@"Finished with query = %@, predicate = %@", _query, _query.predicate);
}
});
}
});
NSLog(@"bb");
return TRUE;
}
- (void)processFiles:(NSNotification *)notification {
[_query disableUpdates];
// The query reports all files found, every time.
NSArray * queryResults = [_query results];
NSLog(@"Results = %@", queryResults);
for (NSMetadataItem * result in queryResults) {
NSURL * fileURL = [result valueForAttribute:NSMetadataItemURLKey];
NSLog(@"file = %@", fileURL);
[_fileArray addObject:fileURL];
}
[self stopQuery];
}
@end
int main(int argc, char *argv[]) {
if (argc != 2) {
NSLog(@"Error in number of params");
return 0;
}
NSString *s = [NSString stringWithFormat:@"%s", argv[1]];
NSLog(@"suffix = %@", s);
FileQuery *q = [FileQuery new];
if ([q startQuery:s]) {
while(true) {
NSLog(@"1");
sleep(100);
}
} else {
NSLog(@"query failed");
}
return 0;
}
出于某种原因,NSMetadataQueryDidFinishGatheringNotification永远不会被调用。
此外,NSMetadataQueryDidUpdateNotification通知也永远不会被调用。
任何人有任何想法,为什么? 有没有人有更好的想法Spotlight搜索文件?
非常感谢!
答
当我做一个修改时,你的代码在我的机器上工作。相反,在循环中调用sleep
的,叫CFRunLoopRun()
:
int main(int argc, char *argv[]) {
...
if ([q startQuery:s]) {
CFRunLoopRun();
} else {
NSLog(@"query failed");
}
return 0;
}
的通知机制是使用运行循环实现的,所以你必须有一个正在运行的为它做它的魔力。