Gregory Higley
Gregory Higley

Reputation: 16588

Why does Spotlight sometimes not run my query?

I'm playing around with the Spotlight API, both the Carbon and Cocoa versions, and I seem to have the same problem crop up every once in a while: The query never runs, and never fires any notifications. However, I want to stress that most of the time it does run, so something strange is going on.

I'm not writing any particular app. This is just a Spotlight test harness, so the query is not fired based on user input. Instead, it's configured and executed in applicationDidFinishLaunching: inside of my controller. Originally I tried to do this in awakeFromNib, but in that case the query never ran. (My theory is that the RunLoop has not started yet, but I'm not sure.)

Here's the code from applicationDidFinishLaunching: for Carbon:

CFStringRef predicate = CFSTR("kMDItemContentTypeTree == 'public.movie'");
_query = MDQueryCreate(NULL, predicate, NULL, NULL);
_query = (MDQueryRef)CFMakeCollectable(_query);
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(notify:)
                                             name:nil
                                           object:(id)_query];
MDQueryExecute(_query, kMDQueryWantsUpdates);

I wrote the above from memory, so it may contain typos that weren't in the original. The original code compiles and runs just fine, except for occasionally not working at all.

What gives? Perhaps applicationDidFinishLaunching: is not the right place for a Spotlight query.

Upvotes: 1

Views: 328

Answers (1)

baldmountain
baldmountain

Reputation: 31

I start a Spotlight query in applicationDidFinishLaunching and have no issues so I don't think that is your problem.

I have a couple things to try. Rather than passing nil to name in addObserver:selector:name:object try passing NSMetadataQueryDidFinishGatheringNotification for name and make a second call passing NSMetadataQueryDidUpdateNotification for name. The first will generate a result when the query finishes running for the first time. The second will provide updates. (But only when something changes.)

Upvotes: 1

Related Questions