[英]Core Data with iCloud Notifications in iOS 7
我已經為我的應用添加了iCloud支持。 當用戶更新他的數據時,我收到了通知NSPersistentStoreDidImportUbiquitousContentChangesNotification
那很棒
但是,我有這些問題
will
版本,我可以用它來顯示加載器,例如數據庫將被更新 will
版本,所以我使用相同的通知顯示加載器告訴用戶數據庫正在更新...此通知中的問題是,如果內容發生更改,可以多次調用它在iCloud中比較大,這導致我顯示幾個加載指示器! 。
我通過這樣做添加了對Core數據的iCloud支持:
在NSManagedObjectContext中
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
_managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy;
在NSPersistentStoreCoordinator中
[_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:@{NSPersistentStoreUbiquitousContentNameKey:@"iCloudStore"} error:nil];
並在NSPersistentStoreDidImportUbiquitousContentChangesNotification
通知方法中
- (void)persistentStoreDidImportUbiquitousContentChanges:(NSNotification *)notification
{
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
[managedObjectContext performBlock:^{
[managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
dispatch_async(dispatch_get_main_queue(), ^{
UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
MBProgressHUD *hud = [MBProgressHUD HUDForView:mainWindow];
if (hud == nil) {
hud = [[MBProgressHUD alloc] initWithWindow:mainWindow];
}
[mainWindow addSubview:hud];
hud.labelText = NSLocalizedString(@"Progress updated", nil);
[hud show:YES];
[hud hide:YES afterDelay:1];
// Post Notification
[[NSNotificationCenter defaultCenter] postNotificationName:RESET_APPLICATION_NOTIFICATION object:nil];
});
}];
}
我找不到這個通知的遺囑版本,我可以用它來顯示加載器,例如數據庫將被更新
是的,那是因為沒有一個。 當新的更改進入時,iCloud守護程序會保存它們, 然后告訴您它做了什么。
由於我找不到遺囑版本,所以我使用相同的通知顯示加載器告訴用戶數據庫正在更新...此通知中的問題是,如果內容發生更改,可以多次調用它在iCloud中比較大,這導致我顯示幾個加載指示器!
是! 我有同樣的問題。 這些通知可能非常頻繁,因此您不希望每次進入時都通知用戶。我所做的是安排延遲通知,直到iCloud安靜至少1秒鍾。 您可以使用NSTimer
執行此操作。 首先將其聲明為屬性:
@property (readwrite, retain) NSTimer *iCloudUpdateTimer;
然后,當您收到“導入”通知時,請執行以下操作:
if (self.iCloudUpdateTimer == nil) {
self.iCloudUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(notifyUser:)
userInfo:nil
repeats:NO];
} else {
[self.iCloudUpdateTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:1.0];
}
// Now actually handle the notification....
這樣做:如果計時器不存在,則創建它。 如果確實存在,則會將開火日期延遲一秒鍾。 當iCloud發送大量通知時,計時器將繼續被推出。 在iCloud平靜下來后,計時器將最終點火一秒鍾。
然后當計時器觸發時,執行以下操作:
- (void)notifyUser:(NSNotification *)notification
{
[self.iCloudUpdateTimer invalidate];
self.iCloudUpdateTimer = nil;
// Then notify the user
}
您可能需要使用dispatch_async
來確保所有計時器訪問都發生在同一隊列中。
(順便說一句,即使有“將導入”通知,它可能會像當前的“導入”通知一樣頻繁發布,所以它對你沒有多大幫助。)
有沒有辦法可以手動觸發iCloud更新?
不,你絕對無法控制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.