2017-06-07 38 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系统中,如果系统检测到其存储空间不足,则会触发“清理”阶段,其中将清除其他应用程序的目录,这在绝大多数情况下都会缓解问题,从而完成该过程。

如果所有这些都失败了,尝试执行压缩将会引发异常;你的错误处理代码应该能够捕捉到。