Как решить проблемы с памятью в iOS Swift при получении данных из базы данных sqlite в представлении коллекции - PullRequest
0 голосов
/ 08 января 2019

Я использую базу данных sqlite, которая содержит более 1000 записей и извлекает данные из ячейки представления коллекции. Я использовал пользовательскую ячейку для отображения данных. Когда я выполняю действия над кнопкой и перезагружаю представление коллекции, у меня чаще всего возникают проблемы с памятью. Поэтому я делюсь своим кодом. Пожалуйста, помогите мне, поскольку я новичок в Swift.

в моем viewDidLoad я заполняю список массивов из базы данных

override func viewDidLoad() {
    super.viewDidLoad()
    // Register cell
    navigationView.dropShadow()
    collectionView.register(UINib(nibName: "HomeViewCell", bundle: nil), forCellWithReuseIdentifier: "HomeViewCell")
    navigationController?.navigationBar.isHidden = true
    appDelegate = UIApplication.shared.delegate as! AppDelegate


    profilesArray.removeAll()
    profileImageArray.removeAll()


    let tempProfilesArray = masterDBObj.retriveMsterData(fromDB: "PROFILE", withGroupName: groupname)


    //Get offers IMG data from local DB / Remove duplicates - sub sets
    let IMGDBObj = TCMasterImageDB()

    var sameProfileSet: Set<AnyHashable> = []
    for i in 0 ..< tempProfilesArray!.count {//tempProfilesArray!.count
        autoreleasepool {
            guard let DBObj = tempProfilesArray![i] as? TCMasterDB else {return}

            guard let IMGArray = IMGDBObj.retriveIMGData(fromDB: "PROFILE", withCode: DBObj.codeString) else {return}
            let destinationName = DBObj.nameString
            if !sameProfileSet.contains(destinationName){
                print("Profile name : \(DBObj.nameString)")
                if !(DBObj.nameString == "25-OH VITAMIN D (TOTAL)" ||  DBObj.nameString == "HbA1c"){

                    profilesArray.append(DBObj)
                    profileImageArray.append(IMGArray)
                    sameProfileSet.insert(destinationName)
                }
            }
        }
    }
}

Эта функция используется для отображения данных в ячейке

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    self.customCell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeViewCell", for: indexPath) as? HomeViewCell

    self.customCell!.configureCell(imageName: self.profilesArray[indexPath.item].nameString, cell: self.customCell!, forItemAtIndexPath: indexPath)

    self.customCell!.lblTes.text! = self.profilesArray[indexPath.row].nameString

    var subIMGArray = self.profileImageArray[indexPath.row] as! Array<Any>
    if subIMGArray.count == 0 {
        self.customCell!.profileImageView.image = UIImage(named: "OfferProfileDefault.png")
    }else{
        var IMGDBObj = TCMasterImageDB()
        IMGDBObj = subIMGArray[0] as! TCMasterImageDB
        self.customCell!.profileImageView.contentMode = .scaleToFill
        self.customCell!.profileImageView.image = ImageManager.imageNamed("OfferProfileDefault.png")
        self.customCell!.profileImageView.loadImage(fromURL: IMGDBObj.imgLocationString!)
    }

    let offerDBObj = self.profilesArray[indexPath.row]
    self.customCell!.testRateLbl.text = "\(offerDBObj.testCountString!) tests @ ₹ \(offerDBObj.rateB2CString!)"

    self.customCell!.addToCartBtn.tag = (indexPath.row)
    self.customCell!.addToCartBtn.addTarget(self, action: #selector(self.myProfileCartAction), for: UIControlEvents.touchUpInside)

    //Offer price

    if TCUtilityManager.retrieve(fromUserDefaults: "USERTYPE") == "LOYALTY"{
        //LOYALTY_DISCOUNT
        let loyaltyDiscout: Float = Float(TCUtilityManager.retrieve(fromUserDefaults: "LDISCOUNT")) ?? 0.0
        let offerRateAmount: Float = Float(offerDBObj.ratePayAmountString)!
        let finalAmount = Int(roundf(offerRateAmount * (loyaltyDiscout / 5)) * 5)

        if finalAmount == 0 {
            if (offerDBObj.rateB2CString == offerDBObj.ratePayAmountString) {
                self.customCell!.testRateLbl.text = "\(offerDBObj.testCountString!) tests @ ₹ \(offerDBObj.rateB2CString!)"
            } else {
                self.customCell!.testRateLbl.text = "\(offerDBObj.testCountString!) tests @ ₹ \(offerDBObj.rateB2CString!)"
            }
        }else{
            if Int(offerDBObj.rateB2CString) == finalAmount {
                self.customCell!.testRateLbl.text = "\(offerDBObj.testCountString!) tests @ ₹ \(finalAmount)"
            } else {
                self.customCell!.testRateLbl.text = "\(offerDBObj.testCountString!) tests @ ₹ \(finalAmount)"
            }

        }

    }else{
        if (offerDBObj.rateB2CString == offerDBObj.ratePayAmountString) {
            self.customCell!.testRateLbl.text = "\(offerDBObj.testCountString!) tests @ ₹ \(offerDBObj.ratePayAmountString!)"
        } else {
            self.customCell!.testRateLbl.text = "\(offerDBObj.testCountString!) tests @ ₹ \(offerDBObj.ratePayAmountString!)"
        }
    }

    //Cart button


    let addToCartValue = offerDBObj.addTestToCartString!
    print("Result : \(addToCartValue)")
    //        autoreleasepool {
    //            DispatchQueue.main.async {
    switch addToCartValue {
    case "TRUE","TRUE_WITHOUT_PROFILE":
        self.customCell!.addToCartBtn.isUserInteractionEnabled = true
        //            customCell!.addToCartBtn.setImage(UIImage(named: "cart_Nav"), for: .normal)//red
        self.customCell!.backgroundColor = #colorLiteral(red: 0.8922533393, green: 0.2110714018, blue: 0.2173824012, alpha: 1)
        self.customCell!.topView.backgroundColor = #colorLiteral(red: 0.8922533393, green: 0.2110714018, blue: 0.2173824012, alpha: 1)
        self.customCell!.lblTes.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        self.customCell!.testRateLbl.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        self.customCell!.addToCartBtn.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        self.customCell!.addToCartBtn.setTitleColor(#colorLiteral(red: 0.8922533393, green: 0.2110714018, blue: 0.2173824012, alpha: 1), for: .normal)
        self.customCell!.addToCartBtn.setTitle("REMOVE", for: .normal)

        break

    case "TRUE_WITH_PROFILE","TRUE_WITH_OFFER","TRUE_WITH_THYRONOMICS":
        self.customCell!.addToCartBtn.isUserInteractionEnabled = false
        self.customCell!.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        self.customCell!.topView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        self.customCell!.lblTes.textColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        self.customCell!.testRateLbl.textColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        self.customCell!.addToCartBtn.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
        self.customCell!.addToCartBtn.setTitleColor(#colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1), for: .normal)
        self.customCell!.addToCartBtn.setTitle("INCLUDE", for: .normal)

        break
    default:
        self.customCell!.addToCartBtn.isUserInteractionEnabled = true
        self.customCell!.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        self.customCell!.topView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        self.customCell!.lblTes.textColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        self.customCell!.testRateLbl.textColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        self.customCell!.addToCartBtn.backgroundColor = #colorLiteral(red: 0.8922533393, green: 0.2110714018, blue: 0.2173824012, alpha: 1)
        self.customCell!.addToCartBtn.setTitleColor(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), for: .normal)
        self.customCell!.addToCartBtn.setTitle("ADD", for: .normal)

        break
    }
    //            }
    //        }

    print("end Result : \(addToCartValue)")

    return customCell! // return your cell
}
...