NSMetadataQuery notification block not called

Hello all


I am having problems using NSMetadataQuery to check cloud states. Consider the code snippet below (originally inspired by the code posted in

http://stackoverflow.com/questions/22112700/how-do-i-create-a-nsmetadataquery-and-get-results-on-a-background-thread):


NSMetadataQuery *query = [[NSMetadataQuery alloc] init];

void (^notificationBlock)(NSNotification __strong *notification) = ^(NSNotification __strong *notification) {

NSLog(@"entering notification block");

};

[query enableUpdates];

NSURL *url = [[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil] URLByAppendingPathComponent: @"Documents"];

NSPredicate *metadataPredicate = [NSPredicate predicateWithFormat:@"%K BEGINSWITH %@", NSMetadataItemPathKey, url.path];

query.notificationBatchingInterval = 1.0;

query.searchScopes = [NSArray arrayWithObject:NSMetadataQueryUbiquitousDataScope];

query.predicate = metadataPredicate;

NSOperationQueue* nsQueue = [NSOperationQueue new];

[[NSNotificationCenter defaultCenter]

addObserverForName:NSMetadataQueryDidFinishGatheringNotification

object:query

queue:nsQueue

usingBlock:notificationBlock

];

[query startQuery];

[NSThread sleepForTimeInterval: 1000.0f];


My expectation would be that the notification block gets called by another thread while the main thread is sleeping. Instead the block is never called. Any help is greatly appreciated.

Accepted Reply

Ah, found the solution for the problem: [query startQuery] wasn't called in the main thread. Replacing the call by


dispatch_sync(dispatch_get_main_queue(), ^{

[query startQuery];

});


solved the issue. It would have been nice if startQuery threw some exception if called by the wrong thread.

Replies

Ah, found the solution for the problem: [query startQuery] wasn't called in the main thread. Replacing the call by


dispatch_sync(dispatch_get_main_queue(), ^{

[query startQuery];

});


solved the issue. It would have been nice if startQuery threw some exception if called by the wrong thread.