首页 > 解决方案 > Swift Realm:线程安全并发读写索引越界

问题描述

我正在尝试在 Realm 数据库上安全地进行并发读写。这就是我想要达到的目标。

我从 Flickr 中提取图像,一旦imageData下载,Photo对象就会被写入 Realm 数据库。我还包括一个notificationinsertions。将 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.synchandleInsertionsWhenNotified. 这样做完全消除了崩溃,但当 UI 在主线程上运行时会冻结 UI。在我的情况下,这并不理想。

标签: iosswiftrealm

解决方案


在更仔细地研究了日志之后,我观察到每当应用程序崩溃时,对象计数都不会计算在内。换句话说,当 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)
        }
    }
}

希望它可以帮助那里的任何人。


推荐阅读