Wednesday, March 19, 2008

Cocoa: spotlight queries

For QNote.app I implemented a built in spotlight search.
With Spotlight it is easy to search for content on the whole computer. I just wanted to restrict it to my notes database. NSMetadataQuery knows the method setSearchScopes: for this. I set the scope to the directory just before starting the query, as I set the search predicate. Unfortunately I always ended up with at most one result, even when I knew that there would be more.

The solution to this was to directly call setSearchScopes: after initializing the query:

_query = [[NSMetadataQuery alloc] init];

// Restrict the search to our working directory
NSString *path = [@"~/Library/QNotes" stringByExpandingTildeInPath];
[_query setSearchScopes:[NSArray arrayWithObjects:path,nil]];


Now I am correctly seeing all results.

Btw.: Ars technica as a nice article about spotlight, even if it ends up in Spotlight gui bashing at the end. But the first half is a good read.


Apple also has a good overview article.

1 comment:

  1. What I want to do is create a NSPredicate, and pass it into some API with a file path to get a boolean result as to whether that file matches the predicate, but I can't seem to find any API that does that.

    Sure, I could use the NSMetadataQuery to pass in the directory of the file, and see if the file I care about is one of the ones returned by the query, but that seems like a very round about way to achieve it.

    Another thing is, I can't see any API that actually returns the Spotlight attributes for a particular file.

    ReplyDelete