Swift iOS - не могу получить доступ к моим классам или уведомлениям из файлов cocoapod - PullRequest
0 голосов
/ 16 февраля 2019

Я скачал 2 совершенно разных модуля, импортировал их в свой проект, использовал их в одном из моих контроллеров представления, и все отлично работает, если я выберу один из них.

первый модуль

второй модуль

Однако, если я пытаюсь получить доступ к тому же контроллеру вида из одного из файлов модуля, тот же контроллер точного вида не распознается.Я также создал и попытался отправить уведомление контроллеру представления, но уведомление не получает ответа (работает нормально, я пробовал его из других созданных мной классов).Затем я создал синглтон под классом файла модуля и затем попытался получить доступ к синглтону, но ничего не произошло (операторы print должны выполняться).

Это случилось с 2 различными файлами модуля, и они оба работают нормально, поэтому яЯ предполагаю, что есть еще одна проблема, которую я пропускаю, которая препятствует работе внешних файлов в модулях?

Модуль отлично работает внутри MyController

import ThePod

class MyController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(printSomethingInMyController(_:)), name: Notification.Name("printSomethingInMyController"), object: nil)

         // the pod works fine
        let podFile = FileWithinThePod()
    }

    @IBAction func buttonTapped(_ sender: UIButton) {

        // the pod does what it's supposed to do
        podFile.startSomeAction()
    }

    @objc fileprivate func printSomethingInMyController(_ notification: Notification) {
        print("notification- this should print in MyController")
    }

    static func printSomethingElse() {
        print("this a class print function")
    }
}

MyController не доступен внутрифайл pod

open class FileWithinThePod {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }
    setUp() {
      // whatever this file needs
    }

    func startSomeAction() {

        // 0. the pod does something and it works fine

        // 1. ***THE PROBLEM IS HERE. I can't access MyController (photo below)
        MyController.printSomethingElse()

        // 2. ***THE PROBLEM IS ALSO HERE. This notification never fires because nothing ever prints
        NotificationCenter.default.post(name: Notification.Name("printSomethingInMyController"), object: nil, userInfo: nil)

        // 3. *** nothing happens with MySingleton because nothing ever prints
        MySingleton.startPrinting()

        // 4. *** same thing nothing prints
        let x = MySingleton.sharedInstance
        x.tryPrintingAgain()
    }
}

class MySingleton {

    static let sharedInstance = MySingleton()

    static func startPrinting() {

        print("print something from MySingleton")

        NotificationCenter.default.post(name: Notification.Name("printSomethingInMyController"), object: nil, userInfo: nil)
    }

    func tryPrintingAgain() {

        print("try again")

        NotificationCenter.default.post(name: Notification.Name("printSomethingInMyController"), object: nil, userInfo: nil)
    }
}

enter image description here

1 Ответ

0 голосов
/ 16 февраля 2019

Это желаемое поведение.Файлы pod (библиотека) не зависят от цели вашего приложения или классов приложения.Он ничего не знает о ваших файлах или классах.

Ваше приложение зависит от этих библиотек, а эти библиотеки не зависят от вашего приложения.Подобное редактирование библиотеки не очень хорошая вещь, потому что на следующих pod update эти изменения могут исчезнуть.

Решение: Добавить исходные файлы из проекта pod в папку приложения.,Не добавляйте их как стручок.

...