Круг удержания делегата при использовании слабых - PullRequest
0 голосов
/ 04 марта 2019

Я работаю с координаторами.Мой ViewController не освобождается, даже если я установил слабых делегатов.

Координатор:

class JournalDetailCoordinator: Coordinator {
    var dependencys: AppDependency
    var navigationController: UINavigationController
    var collectionViewController: CollectionViewWithMenuController!
    var imagePickerManager: ImagePickerManager!




    init(dependencys: AppDependency, navigationController: UINavigationController) {
        self.dependencys = dependencys
        self.navigationController = navigationController

    }

    func start() {
        loadCollectionViewController()
    }

    deinit {
        print("JournalDetailCoordinator deinitialisiert")

    }

    func loadCollectionViewController() {
        var journalDetailViewControllerContainer = [JournalDetailViewController]()
        for journal in dependencys.journals {
            let vc: JournalDetailViewController = dependencys.getJournalDetailDependency().createVC()
            vc.entryJournal = journal
            vc.delegateLoadImagePickerManager = self
            journalDetailViewControllerContainer.append(vc)
        }
        collectionViewController = dependencys.getCollectionViewWithMenuDependency().createVC()
        collectionViewController.managedViewControllers = journalDetailViewControllerContainer
        navigationController.pushViewController(collectionViewController, animated: true)
    }



}

extension JournalDetailCoordinator: LoadImagePickerManager {
    func loadImagePickerManager<T>(vc: T) where T : UIViewController & ImageGetterDelegate {
        imagePickerManager = ImagePickerManager()
        imagePickerManager.delegate = vc
        imagePickerManager.pickImage(viewController: collectionViewController)

    }
}

ViewController:

class JournalDetailViewController: UIViewController {
    lazy var mainView: JournalDetailViewP = {
        let view = JournalDetailViewP()
        return view
    }()

    typealias myType = SetJournal & HasImagePickerManager
    // dependency
    var dep: myType!
    var entryJournal: Journaling!



    var tableViewDataSource: JournalDetailTVDataSource?
    var collectionViewInteraction: AddImageCollectionViewInteraction?

    weak var delegateLoadImagePickerManager: LoadImagePickerManager?

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Detail Journal"
        // only for testing without coordinator connection
        //        if entryJournal == nil {
        //            entryJournal = NewJournal()
        //        }
        //        dep = AppDependency()
        setMainView()
        loadTableView()
        loadCollectionView()

    }
    override func viewDidDisappear(_ animated: Bool) {
        print("view did disappear Journal Detail")
    }

    deinit {
        dep.setJournal(newJournal: entryJournal)
        print("JournalDetailViewController deinitialisiert")
    }


    @objc func getImage() {
        delegateLoadImagePickerManager?.loadImagePickerManager(vc: self)
        //        dep.imagePickerManager.delegate = self
        //        dep.imagePickerManager.pickImage(viewController: self)

    }

    func saveEntry() {

    }

}

extension JournalDetailViewController: Storyboarded {}
extension JournalDetailViewController: DependencyInjectionVC {}
extension JournalDetailViewController: SetMainView {}

extension JournalDetailViewController: ImageGetterDelegate {
    func returnImage(image: UIImage) {
        if entryJournal.image[0] ==  nil {
            entryJournal.image[0] = image
        } else {
            entryJournal.image.append(image)
        }

        loadCollectionView()
    }
}

extension JournalDetailViewController: AddImageCollectionViewInteractionDelegate {
    func deleteImage(index: Int) {
    }

    func addImage() {
        getImage()
    }
}

Они освобождаются, если я не выполняю getImage(), поэтому я думаю, что это является причиной круга хранения.

То есть ImagePickerManager:

protocol ImageGetterDelegate: class {
    func returnImage(image: UIImage)
}

class ImagePickerManager: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    var imagePicker = UIImagePickerController()
    weak var delegate: ImageGetterDelegate?

    override init() {
        super.init()
        print("ImagePickerManager initialisiert")
    }


    deinit {
        print("imagePickerManager deinitialisiert")
    }
    /// use to pick the Image, make sure to use the root ViewController to pass in to
    func pickImage<T:UIViewController>(viewController: T) {
        let alertList = UIAlertController(title: NSLocalizedString("Load Picture", comment: "Picture alert Alertcontroller"), message: nil, preferredStyle: .actionSheet)

        let cameraAction = UIAlertAction(title: "Camera", style: .default) {
            UIAlertAction in self.openCamera(viewController: viewController)
            alertList.dismiss(animated: true, completion: nil)
        }

        let galleryAction = UIAlertAction(title: "Gallery", style: .default) {
            UIAlertAction in self.openGallery(viewController: viewController)
            alertList.dismiss(animated: true, completion: nil)
        }

        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) {
            UIAlertAction in
            alertList.dismiss(animated: true, completion: nil)
        }

        alertList.addAction(cameraAction)
        alertList.addAction(galleryAction)
        alertList.addAction(cancelAction)

        viewController.present(alertList, animated: true, completion: nil)
    }

    private func openCamera<T:UIViewController>(viewController: T) {

        if(UIImagePickerController .isSourceTypeAvailable(.camera)) {
            imagePicker.sourceType = .camera
            imagePicker.delegate = self
            viewController.present(imagePicker, animated: true, completion: nil)
        } else {
            let warningAlert = UIAlertController(title: "Warning", message: "You do not have a camera", preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "Okay", style: .cancel) {
                UIAlertAction in
                warningAlert.dismiss(animated: true, completion: nil)
            }
            warningAlert.addAction(cancelAction)
            viewController.present(warningAlert, animated: true, completion: nil)
        }

    }

    private func openGallery<T:UIViewController>(viewController: T) {
        imagePicker.sourceType = .photoLibrary
        imagePicker.delegate = self
        viewController.present(imagePicker, animated: true, completion: nil)
    }

    @objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        guard let image = info[.originalImage] as? UIImage else {
            print("Expected a dictionary containing an image, but was provided the following: \(info)")
            return
        }
        delegate?.returnImage(image: image)

    }

}

ImagePickerManager не выделяется после освобождения Координатора.Так что я думаю, что Круг удержания - потому что я передаю ViewVontroller обратно через Coordinator в LoadImagePickerManager и затем устанавливаю vc для Coordinator?Кто-нибудь есть идеи, как решить эту проблему или что делать?

Редактировать: LoadImagePickerManager:

protocol LoadImagePickerManager: class {
    func loadImagePickerManager<T: UIViewController & ImageGetterDelegate>(vc: T)
}

Я думаю, что утечка памяти происходит здесь при передаче collectionViewController:

imagePickerManager.pickImage(viewController: collectionViewController)

Поскольку я выполнил некоторые тесты, если я не выполню эту часть, то все нормально удаляется.

Обновлен класс ImagePickerManager:

class ImagePickerManager: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    var imagePicker = UIImagePickerController()
    weak var delegate: ImageGetterDelegate?
    var viewController: UIViewController!

    override init() {
        super.init()
        print("ImagePickerManager initialisiert")
    }


    deinit {
        print("imagePickerManager deinitialisiert")
    }
    /// use to pick the Image, make sure to use the root ViewController to pass in to
    func pickImage<T:UIViewController>(viewController: T) {
        self.viewController = viewController
        let alertList = UIAlertController(title: NSLocalizedString("Load Picture", comment: "Picture alert Alertcontroller"), message: nil, preferredStyle: .actionSheet)

        let cameraAction = UIAlertAction(title: "Camera", style: .default) {
            UIAlertAction in self.openCamera()
            alertList.dismiss(animated: true, completion: nil)
        }

        let galleryAction = UIAlertAction(title: "Gallery", style: .default) {
            UIAlertAction in self.openGallery()
            alertList.dismiss(animated: true, completion: nil)
        }

        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) {
            UIAlertAction in
            alertList.dismiss(animated: true, completion: nil)
        }

        alertList.addAction(cameraAction)
        alertList.addAction(galleryAction)
        alertList.addAction(cancelAction)

        viewController.present(alertList, animated: true, completion: nil)
    }

    private func openCamera() {

        if(UIImagePickerController .isSourceTypeAvailable(.camera)) {
            imagePicker.sourceType = .camera
            imagePicker.delegate = self
            viewController.present(imagePicker, animated: true, completion: nil)
        } else {
            let warningAlert = UIAlertController(title: "Warning", message: "You do not have a camera", preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "Okay", style: .cancel) {
                UIAlertAction in
                warningAlert.dismiss(animated: true, completion: nil)
            }
            warningAlert.addAction(cancelAction)
            viewController.present(warningAlert, animated: true, completion: nil)
        }

    }

    private func openGallery() {
        imagePicker.sourceType = .photoLibrary
        imagePicker.delegate = self
        viewController.present(imagePicker, animated: true, completion: nil)
    }

    @objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        guard let image = info[.originalImage] as? UIImage else {
            print("Expected a dictionary containing an image, but was provided the following: \(info)")
            return
        }
        viewController = nil
        delegate?.returnImage(image: image)

    }

}

Я добавил переменную viewController в класс, и установите его через pickImage (), а затем, когда изображение выбрано, я устанавливаю переменную в ноль.Затем UIViewController освобождается, но класс ImagePickerManager все еще остается активным и не выделяется.

1 Ответ

0 голосов
/ 04 марта 2019

Поскольку вы используете слабый делегат, это никоим образом не приведет к созданию цикла сохранения.

Я думаю, что ваш viewController не освобождается, поскольку ваш viewController все еще находится в стеке вашей навигации.

Попытайтесь удалить все viewControllers из стека навигации, и тогда ваш блок освобождения будет работать как обычно.

Попробуйте следующий код в зависимости от ваших требований (присутствует / нажмите), когда вы возвращаетесь к своемуhomeViewController:

self.navigationController?.popToRootViewController(animated: true)

self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)

Редактировать:

Убедитесь, что ваш протокол относится к типу класса, тогда будет работать только слабая ссылка.

protocol LoadImagePickerManager: class {

}

Вваш PickerManager попытается закрыть, используя следующий код, он перенаправит вас на контроллер rootview, но вы можете снова нажать или представить требуемый viewcontroller:

self.view.window?.rootViewController?.dismiss(animated: false, completion: nil)
...