我们遇到了Realm(Swift)的一个非常奇怪的问题。如果我们在将数据写入数据库之后立即检索它,则它与写入的数据完全不同。有什么可能导致这种情况。下面是调试器发生的截图。获取条目的代码如下所示:
func fetchEntry(assetID: String) throws -> UploadInfo? {
let realm = try Realm()
return realm.objects(UploadInfo.self).filter { $0.assetID == assetID }.first
}
入门课程如下所示:
class UploadInfo: Object {
override static func primaryKey() -> String? {
return "assetID"
}
override static func indexedProperties() -> [String] {
return ["sessionID", "taskID"]
}
@objc dynamic var sessionID: String = ""
@objc dynamic var taskID: Int = 0
@objc dynamic var totalBytesSent: Int64 = 0
@objc dynamic var totalBytesExpectedToSend: Int64 = 0
@objc dynamic var downloadProgress: Float = 0.0
@objc dynamic var uploadProgress: Float = 0.0
@objc dynamic var fileURLPath: String = "" // path of file that is uploaded (i.e. multipart body)
@objc dynamic var path: String = ""
@objc dynamic var assetID: String = "" //PHAsset localIdentifier
@objc dynamic var fileModificationTime: DegooTimestamp = 0
@objc dynamic var fileSize: Int64 = 0 // unprocessedTotalFileDataLength
@objc dynamic var fileChecksumBase64: String = ""
@objc dynamic var fileChecksum: Data = Data(base64Encoded: "")!
var fileURL: URL {
return URL(fileURLWithPath: fileURLPath)
}
func makeCopy() -> UploadInfo {
let ui = UploadInfo()
ui.sessionID = sessionID
ui.taskID = taskID
ui.totalBytesSent = totalBytesSent
ui.totalBytesExpectedToSend = totalBytesExpectedToSend
ui.downloadProgress = downloadProgress
ui.uploadProgress = uploadProgress
ui.fileURLPath = fileURLPath
ui.path = path
ui.assetID = assetID
ui.fileModificationTime = fileModificationTime
ui.fileSize = fileSize
ui.fileChecksumBase64 = fileChecksumBase64
ui.fileChecksum = fileChecksum
return ui
}
}
extension UploadInfo {
var data: Data? {
do {
guard try FileManager.default.isFile(at: self.fileURL) else { return nil }
return try Data(contentsOf: self.fileURL)
} catch {
Log.error(error)
return nil
}
}
var asset: PHAsset? {
return PHAsset.fetchAssets(withLocalIdentifiers: [self.assetID], options: nil).firstObject
}
var shouldBeOptimized: Bool {
guard let asset = self.asset else { return false }
return ImageOptimizer.default.shouldBeReoptimized(width: asset.pixelWidth, height: asset.pixelHeight)
}
func cleanUpUrls() {
for url in urlsToCleanUp {
do {
if FileManager.default.fileExists(atPath: url.absoluteString) {
try FileManager.default.removeItem(at: url)
}
} catch {
Log.error(error)
}
}
}
var urlsToCleanUp: [URL] {
let localAssetPathHelper = LocalAssetPathHelper()
let assetFileName = localAssetPathHelper.fileName(for: URL(fileURLWithPath: self.path))
let multipartBodyFileName = localAssetPathHelper.fileName(for: self.fileURL)
return [
URL(fileURLWithPath: localAssetPathHelper.path(for: multipartBodyFileName)),
URL(fileURLWithPath: localAssetPathHelper.path(for: "/Photos/".appending(assetFileName))),
URL(fileURLWithPath: localAssetPathHelper.path(for: "/Videos/".appending(assetFileName)))
]
}
}
我们已经在Realm 3.1.1和3.5.0上尝试了这个。