2012-07-01 69 views
5

我正在使用iCloud核心數據來同步我的應用程序的數據。如何強制iCloud與核心數據同步?

我嘗試了一切,最後它完美地工作。

但我有一個問題。

有沒有什麼方法可以說要與iCloud同步?

它在應用程序開始時同步,但在其他時間。它似乎是隨機同步的。我找不到自己處理它的方法。

有幫助嗎?

謝謝。

+0

同樣的問題..我也想強制同步 –

回答

0

你必須強迫任何NSURL項目在iCloud中被緩存使用這種方法:

- (BOOL)addBackupAttributeToItemAtURL:(NSURL *)URL 
{ 
    NSLog(@"URL: %@", URL); 
    assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]); 

    NSError *error = nil; 
    BOOL success = [URL setResourceValue: [NSNumber numberWithBool: NO] 
            forKey: NSURLIsExcludedFromBackupKey error: &error]; 
    return success; 
} 

你需要發動對每個目錄這種方法和文件你下載/在文件或資料庫建立目錄。

0

我不相信你能控制使用iCloud和核心數據的同步時間。隨着UIDocument和iCloud我已經用不同程度的成功startDownloadingUbiquitousItemAtURL,但對於核心數據,我不認爲有任何等效 - 我很樂意聽到有人告訴我,否則... ...

1

我想出瞭如何強制核心數據存儲同步到iCloud。您只需要「觸摸」Ubiquity文件系統中Data文件夾中的任何收據文件。下面的代碼將做到這一點。要強制進行同步,請調用syncCloud方法。對於找到的每個「收據」文件,它都會將文件修改時間戳更新爲當前時間,本質上是對文件進行「觸摸」。一旦發生這種情況,iCloud將檢查並同步iCloud中需要同步的任何核心數據文件。據我所知,這是模擬器或Xcode如何選擇「觸發iCloud Sync」選項時的功能。

@property (strong, nonatomic) NSMetadataQuery *query; 

-(void) init 
{ 
    self.query = [[NSMetadataQuery alloc] init]; 

    [[NSNotificationCenter defaultCenter] addObserver: self 
              selector: @selector(didFinishMetadataQuery) 
               name: NSMetadataQueryDidFinishGatheringNotification 
               object: self.query]; 
} 

-(void) didFinishMetadataQuery 
{ 
    // Query completed so mark it as completed 
    [self.query stopQuery]; 

    // For each receipt, set the modification date to now to force an iCloud sync 
    for(NSMetadataItem *item in self.query.results) 
    { 
     [[NSFileManager defaultManager] setAttributes: @{NSFileModificationDate:[NSDate date]} 
             ofItemAtPath: [[item valueForAttribute: NSMetadataItemURLKey] path] 
               error: nil]; 
    } 
} 

-(void) syncCloud 
{ 
    // Look for files in the ubiquity container data folders 
    [self.query setSearchScopes:@[NSMetadataQueryUbiquitousDataScope]]; 

    // Look for any files named "receipt*" 
    [self.query setPredicate:[NSPredicate predicateWithFormat:@"%K like 'receipt*'", NSMetadataItemFSNameKey]]; 

    // Start the query on the main thread 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     BOOL startedQuery = [self.query startQuery]; 
     if (!startedQuery) 
     { 
      NSLog(@"Failed to start query.\n"); 
      return; 
     } 
    }); 
}