在两个类之间快速共享信息

标签 swift class inheritance

我现在正在开发一个选项卡式 View 应用程序,我想知道是否有任何方法可以将我的 FirstViewController.swift 中的信息共享到我的 SecondViewController.swift ?因为我知道 swift 不支持多类继承,所以有没有办法可以在 SecondViewController 中使用 FirstViewController 上的变量和信息?

最佳答案

您需要在 View Controller 上下文之外的模型来存储数据,然后需要一种方法来使用该数据填充这些 View Controller 并提供对模型的引用以从 View Controller 进行更改。您可以通过创建一个符合 UITabBarColtronnerDelegate 的新模型对象来实现此目的,该对象将允许您在选择 View Controller 后访问该 View Controller 。通过将这些关系抽象为协议(protocol)来保持事物的解耦,然后允许您的实现随着应用程序的扩展而独立变化。

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    let applicationModel = ApplicationModel()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        if let tabBarController = window?.rootViewController as? UITabBarController {
            tabBarController.delegate = applicationModel
        }
        return true
    }
}

protocol TabbedViewControllerDelegate {
    var message: String { set get }
}

class ApplicationModel: NSObject, UITabBarControllerDelegate, TabbedViewControllerDelegate {

    var message = "Hello World!"

    func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
        if var tabbedViewController = viewController as? TabbedViewController {
            tabbedViewController.message = message
            tabBarController.delegate = self
        }
    }
}

protocol TabbedViewController {
    var message: String { set get }
    var delegate: TabbedViewControllerDelegate? { get set }
}

class FirstViewController: UIViewController, TabbedViewController {

    var delegate: TabbedViewControllerDelegate?

    var message: String = "" {
        didSet {
            println( "FirstViewController populated with message: \(message)" )
        }
    }

    @IBAction func buttonPressed( sender: AnyObject? ) {
        self.delegate?.message = "Updated message from FirstViewController"
    }
}

class SecondViewController: UIViewController, TabbedViewController {

    var delegate: TabbedViewControllerDelegate?

    var message: String = "" {
        didSet {
            println( "SecondViewController populated with message: \(message)" )
        }
    }

    @IBAction func buttonPressed( sender: AnyObject? ) {
        self.delegate?.message = "Updated message from SecondViewController"
    }
}

关于在两个类之间快速共享信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31551355/

相关文章:

Python初始化

javascript - 在 Javascript 中获取派生构造函数的名称

objective-c - 我不想重新加载 View Controller

ios - 在展开可选值时发现 nil - spriteKit

java - 在Java中,如何使子类的实例变量具有子类的类型,而不是父类(super class)的类型?

c# - 创建我创建的窗口的新实例。多次调用做不同的事情

javascript - 对象被 JavaScript 中的后续对象覆盖

c++ - 没有用于调用的匹配函数...继承的 C++ 类中缺少重载

swift - 如何测试 Swift 字典中是否不存在键?

swift - 什么会导致 Xcode MacOs 应用程序将主包指向 "/Applications/Xcode.app"?