2017-06-07 35 views
1

文檔中的示例(https://realm.io/docs/swift/latest/#compacting-realms)對我來說不是很清楚,因爲我不知道是否可以在應用程序使用期間始終調用壓縮,或者在啓動時只調用一次壓縮。下面的實現是否正確,或者做一個單獨的配置,包括shouldCompactOnLaunch在應用啓動時調用一次會更好。如何在RealmSwift中正確使用shouldCompactOnLaunch

如果我將shouldCompactOnLaunch添加到默認配置中,每次創建領域實例時都會看到被調用的塊。

 Realm.Configuration.defaultConfiguration = Realm.Configuration(schemaVersion: schemaVersion, migrationBlock: migrationBlock,shouldCompactOnLaunch: { totalBytes, usedBytes in 
     // totalBytes refers to the size of the file on disk in bytes (data + free space) 
     // usedBytes refers to the number of bytes used by data in the file 

     // Compact if the file is over 100MB in size and less than 50% 'used' 
     let oneHundredMB = 100 * 1024 * 1024 
     print ("totalbytes \(totalBytes)") 
     print ("usedbytes \(usedBytes)") 
     if (totalBytes > oneHundredMB) && (Double(usedBytes)/Double(totalBytes)) < 0.7{ 
      print("will compact realm") 
     } 
     return (totalBytes > oneHundredMB) && (Double(usedBytes)/Double(totalBytes)) < 0.7 
    }) 
    do { 
     // Realm is compacted on the first open if the configuration block conditions were met. 
     _ = try Realm(configuration: config) 
    } catch { 
     // handle error compacting or opening Realm 
    } 

還有一件事對我很有趣:如果壓實失敗會發生什麼?太少的存儲將是一個原因。我仍然可以訪問數據,壓縮只會被忽略嗎?

回答

0

所以我的解決方案是創建配置。配置爲相同,但應爲緊急啓動塊的。這個配置與shouldCompactOnLaunch我只使用一次在應用程序啓動,所以它不會被觸發每次。

這裏是鏈接到Realm github issue

如果壓實失敗應用程序將繼續使用數據庫的未壓實版本。

1

有一個在RLMRealmConfiguration頭文件的其他信息:

/** 
A block called when opening a Realm for the first time during the life 
of a process to determine if it should be compacted before being returned 
to the user. It is passed the total file size (data + free space) and the total 
bytes used by data in the file. 

Return `YES` to indicate that an attempt to compact the file should be made. 
The compaction will be skipped if another process is accessing it. 
*/ 

@property (nonatomic, copy, nullable) RLMShouldCompactOnLaunchBlock shouldCompactOnLaunch; 

誠然,我們應該讓該網站,該塊只應在第一時間呼籲文檔中更加明顯一Realm實例代表一個特定的Realm文件被創建。

如果您確實看到此塊被多次調用相同的Realm文件,請在Realm Cocoa GitHub page上打開一個問題,其中包含詳細的重現步驟。

一旦您創建了具有特定ConfigurationRealm實例,通常最佳做法是避免在事實之後變更該配置。您不應創建兩個不同的對象,一個帶壓實塊,另一個不帶。 Realm內部緩存基於ConfigurationRealm實例,因此可能會導致無法預知的行爲。

壓縮不應該失敗。如果您的設備已經快要耗盡硬盤空間,那麼這將成爲問題的唯一主要情況是。根據該領域中的空白空間的多少,壓縮領域通常顯着更小,因此整個操作不需要2倍的存儲大小。在iOS系統中,如果系統檢測到其存儲空間不足,則會觸發「清理」階段,其中將清除其他應用程序的目錄,這在絕大多數情況下都會緩解問題,從而完成該過程。

如果所有這些都失敗了,嘗試執行壓縮將會引發異常;你的錯誤處理代碼應該能夠捕捉到。