Can I block on a Spotlight NSMetadataQuery?
I have created an NSMetadataQuery
to search for all audio available through Spotlight, modelled on the following command, which returns plenty of results:
mdfind kMDItemContentTypeTree == "public.audio"
Here is the code I'm using:
NSMetadataQuery * q = [[[NSMetadataQuery alloc] init] autorelease];
[q setPredicate:[NSPredicate predicateWithFormat:@"kMDItemContentTypeTree == 'public.audio'", nil]];
NSLog(@"%@", [[q predicate] predicateFormat]);
if ([q startQuery])
while ([q isGathering]) {
NSLog(@"Polling results: %i"开发者_运维技巧, [q resultCount]);
[NSThread sleepForTimeInterval: 0.1];
}
[q stopQuery];
}
For some reason, the query seems to remain in the gathering phase indefinitely, and never gets a single result. I would like to know why this is the case, and whether there would be a more elegant way to block the thread while waiting for a result, preferably avoiding polling.
My application is actually not based on Cocoa but on NSFoundation, and thus far has no event loop. I realize that the conventional approach to dealing with Spotlight queries is to subscribe to an event notification, but I don't know how to block while waiting for one, and that approach seems a little overkill for my purposes.
To phrase my question as simply as possible, can I block my thread while waiting for the NSMetadataQuery
to conclude the initial gathering phase? If so, how?
Instead of [NSThread sleepForTimeInterval:0.1]
try:
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
The former is actually stopping the thread altogether, which means the query can't be running. The latter is kind of like sleeping, except that it also allows event sources to fire.
精彩评论