用例:
我有一个“收藏夹”按钮,当收藏夹按钮再次按下时,它将变为“收藏夹”并删除记录。当我重新收藏它时,它应该再次插入对象,但是它在下面指责了这个错误
发生错误并崩溃:
2019-02-20 09:58:44.348244-0300 Project[3851:768454] *** Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.'
*** First throw call stack:
(0x1babecec4 0x1b9dbda40 0x101681788 0x101683208 0x100565728 0x1006aea94 0x1006aeae4
libc++abi.dylib: terminating with uncaught exception of type NSException
struct FavoriteTool {
private let disposeBag = DisposeBag()
var didLoadFavorites: (([Tool]) -> Void)?
private let disposeBag = DisposeBag()
var didLoadFavorites: (([Tool]) -> Void)?
func isFavorite(favoriteTool: FavoriteTool) -> Observable<Results<FavoriteTool>> {
return favorites(filter: "id == '\(favoriteTool.id)'")
}
func favorite(favoriteTool: FavoriteTool) {
Observable.just(favoriteTool)
.subscribe(Realm.rx.add())
.disposed(by: disposeBag)
}
func unfavorite(favoriteTool: FavoriteTool) {
favorites(filter: "id == '\(favoriteTool.id)'")
.subscribe(Realm.rx.delete())
.dispose()
}
func favorites(filter predicateFormat: String? = nil) -> Observable<Results<FavoriteTool>> {
guard let realm = try? Realm() else {
return Observable.empty()
}
var results: Results<FavoriteTool> = realm.objects(FavoriteTool.self)
if let predicate = predicateFormat {
results = results.filter(predicate)
}
return Observable.collection(from: results)
}
}