Querying with spotlight

481 views Asked by At

I'm working on a tiny project for LEOPARD (10.5) and I'm kinda rookie with Objective-C programming. I've been searching for some tutorials on internet but I'm still confused! I need to use Leopard's spotlight feature to search for every .app file installed at the user's computer. I also need its name, path and icon. All queried data must be saved in a text file. How can I do that??? Thank you!

1

There are 1 answers

0
nst On BEST ANSWER

Define the query, and observe the query termination.

- (void)searchApplications {
    NSMetadataQuery *query = [[NSMetadataQuery alloc] init];
    query.predicate = [NSPredicate predicateWithFormat:@"kMDItemContentTypeTree == 'com.apple.application'"];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(queryDidFinish:)
                                                 name:NSMetadataQueryDidFinishGatheringNotification
                                               object:query];

    [query startQuery];
}

In the query termination function, loop through the results and extract the data you want.

- (void)queryDidFinish:(NSNotification *)notification {

    NSMetadataQuery *query = (NSMetadataQuery *)[notification object];

    [query stopQuery];

    NSMutableArray *paths = [NSMutableArray array];

    for(NSMetadataItem *mdItem in query.results) {
        NSString *name = [mdItem valueForAttribute:(NSString *)kMDItemDisplayName];
        NSString *path = [mdItem valueForAttribute:(NSString *)kMDItemPath];
        NSImage *icon = [[NSWorkspace sharedWorkspace] iconForFile:path];

        [paths addObject:path];
    }

    [query release];

    [paths writeToFile:@"/tmp/applications.txt" atomically:YES];
}