我正在工作的应用程序中,我必须保存图像本地,我使用的领域为此,该应用程序采取让我们说,10到40图像一次从图库,并开始写入图像到领域本地数据库和冻结的屏幕在写入过程中,请我如何修改我的代码,使我的应用程序不会冻结在写入事务期间,我被困在这种情况下,任何帮助将不胜感激,谢谢
let imagesAdd = refObject.1
let imageobjectArray = modelObject as! [FacilitiesImagesModel]
do{
for imageObject in imageobjectArray{
try realmObj.write {
imagesAdd?.facilitiesImages.append(imageObject)
}
}
completionHandler(true, "")
}catch let err{
realmObj.cancelWrite()
completionHandler(false, err.localizedDescription)
}
以下是我的完整方法,我删除了不属于我的问题的额外代码
struct RealmCRUD {
private let realmObj = try! Realm()
func create<T>(modelObject: T, modelObjectType: ModelType, refObject: (PropertyModel?, FacilitiesModel?), completionHandler: @escaping ((Bool, String) -> Void)){
switch modelObjectType {
case .FacilitiesImagesModel:
let imagesAdd = refObject.1
let imageobjectArray = modelObject as! [FacilitiesImagesModel]
do{
for imageObject in imageobjectArray{
try realmObj.write {
imagesAdd?.facilitiesImages.append(imageObject)
}
}
completionHandler(true, "")
}catch let err{
realmObj.cancelWrite()
completionHandler(false, err.localizedDescription)
}
break
}
default:
break
}
我正在从其他类调用此方法,如下所示:
func dismissComplete() {
var arrayOfFacilitiesImagesModelObj = [FacilitiesImagesModel]()
for photos in self.selectedAssets{
if let photo = photos.fullResolutionImage{
let facilitiesImagesModelObj = FacilitiesImagesModel()
facilitiesImagesModelObj.facilityPhoto = photo.jpegData(compressionQuality: 0.5)!
arrayOfFacilitiesImagesModelObj.append(facilitiesImagesModelObj)
}else{
print("Unable to select facility photos")
}
}
self.realmCrudObj.create(modelObject: arrayOfFacilitiesImagesModelObj, modelObjectType: .FacilitiesImagesModel, refObject: (nil,self.realmFacilitiesResults), completionHandler: { (success, error) in
self.collectionViewReference?.reloadData()
ProgressHUD.dismiss()
if !success{
self.showAlert(title: "Error", description: error)
}
})
}
并且我将选择的属性数据传递给这个类中的这个变量
var realmFacilitiesResults: FacilitiesModel?
这是我的设施模型
class FacilitiesModel: Object {
@objc dynamic var facilityName = ""
let facilitiesImages = List<FacilitiesImagesModel>()
let parentProperty = LinkingObjects(fromType: PropertyModel.self, property: "facilities")
}
1条答案
按热度按时间mu0hgdu01#
您的部分问题是您正在进行多个领域写入。您应该为您的所有对象执行一个领域写入。
如果这仍然不能加快速度,那么您应该将对象添加到后台线程中的领域中。但是因为您将在新的线程中操作,所以您必须获得线程安全的引用。