简体   繁体   English

在 VIewControllers 之间共享数据 - iOS

[英]Sharing data between VIewControllers - iOS

For any object created I generally use two two scopes 1) Singleton 2) {local scope}.对于创建的任何对象,我通常使用两个两个作用域 1) 单例 2) {局部作用域}。 I am looking for something in between.我正在寻找介于两者之间的东西。

Say I have one object that 5 view controllers are editing.假设我有 5 个视图控制器正在编辑的一个对象。 I want to share an object between view controllers without having to pass it between view controllers.我想在视图控制器之间共享一个对象,而不必在视图控制器之间传递它。 But it should not also live throughout application since once I am done editing the object i don't need it anymore.但它不应该在整个应用程序中都存在,因为一旦我完成了对象的编辑,我就不再需要它了。

I don't want to inherit all view controller from another class an create a variable there.我不想从另一个类继承所有视图控制器并在那里创建一个变量。 Since view controller are reusable for different objects.由于视图控制器可用于不同的对象。 I want to create an object that comes to life before launch of first view controller, lives throughout the scope of 5 view controllers and then dies after I have saved it someway.我想创建一个在启动第一个视图控制器之前活跃的对象,在 5 个视图控制器的范围内活跃,然后在我以某种方式保存它之后消亡。 Is there anyways I could do this in iOS.无论如何我可以在iOS中做到这一点。

An alternative is to use your AppDelegate.另一种方法是使用您的 AppDelegate。 Within it you can declare a global var than 2 functions, a first one to get the current value and another one to set the value.在其中,您可以声明一个全局变量而不是 2 个函数,第一个用于获取当前值,另一个用于设置值。

It might give something like this:它可能会给出这样的东西:

// Get AppDelegate instance
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate;

// Use your getter to get the current value
var something = appDelegate.getYourStuff();

// Or use a setter to set it, a modifier to modify oit
appDelegate.setYourStuff(yourStuff);
appDelegate.modifiyYourStuffAttribute(newAttributeValue); 

Don't realize if such a method is a bad practice or not, but it works for me.不知道这样的方法是否是一种不好的做法,但它对我有用。

Open to other suggestions!打开其他建议!

As Mat said you can do is in that what.正如 Mat 所说,你能做的就是在那个什么。 For me better is to create specific class for that that will do one particular job.对我来说更好的是创建特定的类来完成一项特定的工作。

class EditingSession {
    class Factory {
        private static let session = EditingSession() //do it lazy
        static func create() -> EditingSession {
            return session
        }
    }

    func openSession() {

    }

    func endSession {

    }

    func getData () -> AnyObject {
        ...
    }
}
  1. In editing session create private initializer.在编辑会话中创建私有初始化程序。 Factory should give the shared instance.工厂应该提供共享实例。

  2. You can pass this class to your ViewControllers and manipulate with the data.您可以将此类传递给您的 ViewControllers 并使用数据进行操作。 You can inject it or just set as property in your VC or VM.您可以注入它,也可以将其设置为 VC 或 VM 中的属性。

  3. If you are done with editing you should end session and clear data or other stuff.如果您完成了编辑,您应该结束会话并清除数据或其他内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM