自分のアプリケーションからSpotlightを利用する

Thousandが標準で「ライブラリ」以下にログを置いていたためにSpotlight検索で引っかからなかったことは前述の通り。しかしそれはスコープの問題であり、あくまでメニューバー右上のSpotlightのスコープには「ライブラリ」以下が入っていないだけである*1。じゃあThousand内部からSpotlightを利用して、スコープもちゃんとログフォルダを指定してやれば検索は出来るってことになる。
CocoaアプリからSpotlightを利用するには多分NSMetadataQueryを使うのが手っ取り早い。NSMetadataQueryを使うには、まずNSPredicateを用意する。

NSPredicate * predicate = [NSPredicate predicateWithFormat:
                               @"kMDItemContentType == 'jp.natori.thousand.thread'"];
    if (_searchString != nil) {
        NSPredicate * subPredicate = [NSPredicate predicateWithFormat:
                                      @"kMDItemTextContent like[cd] %@", 
                                      [_searchString stringByAppendingString:@"*"]];
        predicate = [NSCompoundPredicate andPredicateWithSubpredicates:
                     [NSArray arrayWithObjects:predicate, subPredicate, nil]];

これで書類のタイプと、文字列を含む検索条件を指定したNSPredicateができる。

if (!_query) {
		_query = [[NSMetadataQuery alloc] init];
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(queryDidUpdate:)
													 name:nil
												   object:_query];
		
		[_query setValueListAttributes:
		 [NSArray arrayWithObjects:
		  (id)kMDItemContentType,
		  (id)kMDItemDisplayName,
		  @"jp_natori_Thousand_thread_threadInternalPath",
		  @"jp_natori_Thousand_thread_resCount",
		  @"jp_natori_Thousand_thread_label",
		  nil]];
	}
	[_query setSearchScopes:[NSArray arrayWithObject:[NSString appLogFolderPath]]];
	[_query setPredicate:predicate];
	[_query startQuery];

NSMetadataQueryを作って、スコープや拾ってくるメタデータや、ソートディスクリプタ、NSPredicateを設定したらstartQueryする。以降はNotificationで進捗をモニターすることになる。

でこれをThousandに組み込み中。

*1:Mailとかは入ってるんだろうな