ios - Swift Realm:线程安全并发读写索引越界
问题描述
我正在尝试在 Realm 数据库上安全地进行并发读写。这就是我想要达到的目标。
我从 Flickr 中提取图像,一旦imageData
下载,Photo
对象就会被写入 Realm 数据库。我还包括一个notification
听insertions
。将 Photo 对象写入 Realm 后,更新该项目的transport
属性。但是,我的实现偶尔会崩溃,即每执行 3-5 次就会崩溃一次。
代码如下:
override func viewDidLoad() {
super.viewDidLoad()
subscribeToRealmNotifications()
}
fileprivate func subscribeToRealmNotifications() {
do {
let realm = try Realm()
let results = realm.objects(Photo.self)
token = results.observe({ (changes) in
switch changes {
case .initial:
self.setupInitialData()
self.collectionView.reloadData()
case .update(_, _, let insertions, _):
if !insertions.isEmpty {
self.handleInsertionsWhenNotified(insertions: insertions)
}
case .error(let error):
self.handleError(error as NSError)
}
})
} catch let error {
NSLog("Error subscribing to Realm Notifications: %@", error.localizedDescription)
}
}
fileprivate func handleInsertionsWhenNotified(insertions: [Int]) {
let lock = NSLock()
let queue = DispatchQueue(label: "queue", qos: .userInitiated) //Serial queue
queue.async(flags: .barrier) {
do {
let realm = try Realm()
let objects = realm.objects(Photo.self)
lock.lock()
for insertion in insertions {
print(insertion, objects.count, objects[insertion].id ?? "")
let photo = objects[insertion] //Crash here
self.update(photo: photo)
}
lock.unlock()
} catch let error {
NSLog("Error updating photos in Realm Notifications", error.localizedDescription)
}
}
}
func update(photo: Photo) {
do {
let realm = try Realm()
let updatedPhoto = createCopy(photo: photo)
let transport = Transport()
transport.name = searchText
updatedPhoto.transport = transport
try realm.write {
realm.add(updatedPhoto, update: true)
}
} catch let error {
NSLog("Error updating photo name on realm: %@", error.localizedDescription)
}
}
func createCopy(photo: Photo) -> Photo {
let copiedPhoto = Photo()
copiedPhoto.id = photo.id
copiedPhoto.farm = photo.farm
copiedPhoto.server = photo.server
copiedPhoto.secret = photo.secret
copiedPhoto.imageData = photo.imageData
copiedPhoto.name = photo.name
return copiedPhoto
}
//On push of a button, call fetchPhotos to download images.
fileprivate func fetchPhotos() {
FlickrClient.shared.getPhotoListWithText(searchText, completion: { [weak self] (photos, error) in
self?.handleError(error)
guard let photos = photos else {return}
let queue = DispatchQueue(label: "queue1", qos: .userInitiated , attributes: .concurrent)
queue.async {
for (index, _) in photos.enumerated() {
FlickrClient.shared.downloadImageData(photos[index], { (data, error) in
self?.handleError(error)
if let data = data {
let photo = photos[index]
photo.imageData = data
self?.savePhotoToRealm(photo: photo)
DispatchQueue.main.async {
self?.photosArray.append(photo)
if let count = self?.photosArray.count {
let indexPath = IndexPath(item: count - 1, section: 0)
self?.collectionView.insertItems(at: [indexPath])
}
}
}
})
}
}
})
}
fileprivate func savePhotoToRealm(photo: Photo) {
do {
let realm = try Realm()
let realmPhoto = createCopy(photo: photo)
try realm.write {
realm.add(realmPhoto)
print("Successfully saved photo:", photo.id ?? "")
}
} catch let error {
print("Error writing to photo realm: ", error.localizedDescription)
}
}
注意上面的代码每3-5次崩溃一次,所以我怀疑读写没有安全完成。崩溃时的打印日志和错误日志如下所示
Successfully saved photo: 45999333945
4 6 31972639607
6 7 45999333945
Successfully saved photo: 45999333605
Successfully saved photo: 45999333675
7 8 45999333605
8 9 45999333675
Successfully saved photo: 45999333285
Successfully saved photo: 33038412228
2019-01-29 14:46:09.901088+0800 GCDTutorial[24139:841805] *** Terminating app due to uncaught exception 'RLMException', reason: 'Index 9 is out of bounds (must be less than 9).'
有人能帮忙告诉我哪里出错了吗?
注意:我试过queue.sync
在handleInsertionsWhenNotified
. 这样做完全消除了崩溃,但当 UI 在主线程上运行时会冻结 UI。在我的情况下,这并不理想。
解决方案
在更仔细地研究了日志之后,我观察到每当应用程序崩溃时,对象计数都不会计算在内。换句话说,当 Realm 通知插入时打印的总对象数是 9(即使通过浏览器物理检查领域数据库显示超过 9),但插入索引是 9。
这意味着当进行查询时,对象计数可能还没有更新(不太清楚为什么)。在阅读了有关领域文档和此处的更多文章后,我realm.refresh()
在查询对象之前实现了。这解决了问题。
//Updated code for handleInsertionsWhenNotified
fileprivate func handleInsertionsWhenNotified(insertions: [Int]) {
let lock = NSLock()
let queue = DispatchQueue(label: "queue", qos: .userInitiated) //Serial queue
queue.async(flags: .barrier) {
do {
let realm = try Realm()
realm.refresh() // Call refresh here
let objects = realm.objects(Photo.self)
lock.lock()
for insertion in insertions {
print(insertion, objects.count, objects[insertion].id ?? "")
let photo = objects[insertion] //Crash here
self.update(photo: photo)
}
lock.unlock()
} catch let error {
NSLog("Error updating photos in Realm Notifications", error.localizedDescription)
}
}
}
希望它可以帮助那里的任何人。
推荐阅读
- python - 如何将谷歌脚本复制到其他谷歌表格?
- scala - Scala 中函数类型的类型别名
- git - 在 git 中如何将 Feature 分支合并到 Main 分支然后重新同步
- python - 根据字符删除存储在 pandas 列中的列表元素
- asp.net-core - 在 IIS 上使用托管模型 OutOfProcess 运行 ASP.NET Core gRPC 服务时出现“HTTP 错误 502.3 - 网关错误”
- regex - 权限在 root 上被拒绝,在 find 中使用更具体的正则表达式
- android - Transformations.distinctUntilChanged() 不适用于 equals() 覆盖
- python - Selenium 4 + Python:如何在将网站打印为 PDF 之前压缩图像?
- ab-testing - 了解 AB 测试输出和后续步骤
- html - 我怎样才能在星形内写字