我正在尝试一些代码来使用 NSMetaDataQuery 来获取基于捆绑标识符的应用程序路径。我在关注苹果开发网站中的示例代码:静态聚光灯搜索实现。
我为它写了以下文件
//AppPath.h
void GetAppPath();
@interface SearchQuery: NSObject
{
}
@property (copy) NSMetaDataQuery *metaData;
-(void) initiateSearch;
-(void) queryDidUpdate:sender;
-(void) initalGatherComplete:sender;
@end
定义如下:
void GetAppPath()
{
SearchQuery *query = [[SearchQuery alloc] init];
[query initiateSearch];
}
@Implementation SearchQuery
// Initialize Search Method
- (void)initiateSearch
{
// Create the metadata query instance. The metadataSearch @property is
// declared as retain
self.metadataSearch=[[[NSMetadataQuery alloc] init] autorelease];
// Register the notifications for batch and completion updates
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(queryDidUpdate:)
name:NSMetadataQueryDidUpdateNotification
object:self.metadataSearch];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(initalGatherComplete:)
name:NSMetadataQueryDidFinishGatheringNotification
object:self.metadataSearch];
// Configure the search predicate to find all application with the given
//Bundle Id
NSPredicate *searchPredicate;
searchPredicate=[NSPredicate predicateWithFormat:@"NSApplicationBundleIdentifier == 'com.myapp.app'"];
[self.metadataSearch setPredicate:searchPredicate];
// Begin the asynchronous query
[self.metadataSearch startQuery];
}
// Method invoked when notifications of content batches have been received
- (void)queryDidUpdate:sender;
{
NSLog(@"A data batch has been received");
}
// Method invoked when the initial query gathering is completed
- (void)initalGatherComplete:sender;
{
// Stop the query, the single pass is completed.
[self.metadataSearch stopQuery];
// Process the content.
NSUInteger i=0;
for (i=0; i < [self.metadataSearch resultCount]; i++) {
//Do Something with the result
}
// Remove the notifications to clean up after ourselves.
// Also release the metadataQuery.
// When the Query is removed the query results are also lost.
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSMetadataQueryDidUpdateNotification
object:self.metadataSearch];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSMetadataQueryDidFinishGatheringNotification
object:self.metadataSearch];
self.metadataSearch=nil;
}
@end
我正在调用中的GetAppPAth
方法main
。我已经添加了必要的头文件。代码编译并运行,但我没有收到两个观察者的任何通知。我在两种方法中设置了断点queryDidUpdate
& initalGatherComplete
。但他们永远不会被击中。我认为失败是因为我的主要代码没有等待搜索完成。但即使我在 main 中进行了一些等待,它也无法正常工作。我还尝试了以下问题中的代码:不太了解 NSMetadataQuery
但它以无限while
循环结束。