我正在使用iCloud文档服务同步两台设备。 在代码中,我添加了NSMetadataQueryDidFinishGatheringNotification和NSMetadataQueryDidUpdateNotification。但从未调用过NSMetadataQueryDidUpdateNotification。
代码:
- (void)loadGrocery{
//0. initialize NSMetadataQuery
self.query = [[NSMetadataQuery alloc] init];
//1. set its searchScopes to iCloud's Document directories
[self.query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
//2. set its predicate (match certain file name)
NSPredicate *pred = [NSPredicate predicateWithFormat:@"%K LIKE 'Item_*'",NSMetadataItemFSNameKey];
[self.query setPredicate:pred];
//3.1 add notification when NSMetadataQuery finished gathering
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryDidFinishGathering:) name:NSMetadataQueryDidFinishGatheringNotification object:self.query];
//3.2 add notification when NSMEtadataQuery detects a update
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryDidFinishUpdating:) name:NSMetadataQueryDidUpdateNotification object:self.query];
//4. start query
[self.query startQuery];
}
//3.1 handle the notification when NSMetadataQuery finished gathering
-(void)queryDidFinishGathering:(NSNotification *) notification{
NSLog(@"query did finish gathering");
//1. query: disable and stop
[self.query disableUpdates];
[self.query stopQuery];
//2. query: remove the observer
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSMetadataQueryDidFinishGatheringNotification object:self.query];
//3. query: handle the result
[self loadData:self.query];
[self.query startQuery];
}
//3.2 handle the notification when NSMetadataQuery finish updating
-(void)queryDidFinishUpdating:(NSNotification *)notification{
NSLog(@"query did finish updating");
[self.query stopQuery];
[self loadData:self.query];
[self.query startQuery];
}
insertNewObject方法如下,保存到iCloud文件,因此应在此之后进行更新。
- (void)insertNewObject:(id)sender {
NSLog(@"insertNewObject");
GroceryItem *newGroceryItem = [GroceryItem createNewItem];
[newGroceryItem saveToURL:[newGroceryItem fileURL] forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if(success){
NSLog(@"save newGroceryItem success");
[newGroceryItem openWithCompletionHandler:^(BOOL success) {
if(success){
NSLog(@"open newGroceryItem success");
[self.objects insertObject:newGroceryItem atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}else{
NSLog(@"open newGroceryItem failed");
}
}];}
else{
NSLog(@"open newGroceryItem failed");
}
}];
}
在这段代码中,我需要在收到NSMetadataQueryDidFinishGatheringNotification时只加载一次数据。因此,我删除了此通知的观察者。但是对于NSMetadataQueryDidUpdateNotification,在调用insertNewObject方法后,当我在两个不同的设备上运行时(iCloud都已启用),从不调用方法 - (void)queryDidFinishUpdating:(NSNotification *)通知。谁能告诉我为什么?这是Cesare Rocchi编写的“iCloud for Developers”一书中的示例项目。