我正在尝试使用NSMetaDataQuery来获取基于应用程序路径的代码 在bundle标识符上。我正在关注苹果开发中发现的示例代码 site:Static Spotlight搜索实现。
我为它写了以下文件
//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
&amp; initalGatherComplete
。但他们永远不会受到打击。我以为失败是因为我的主要代码不是
等待搜索完成。但即使我在主要部分等待一段时间,它也无法正常工作。我还尝试过以下问题中的代码:Not quite understanding NSMetadataQuery
但它以无限while
循环结束。
答案 0 :(得分:0)
从您发布的代码示例中,看起来SearchQuery不会被任何内容保留,因此会立即取消分配。