创建一个对象的新实例并将其放入带有 swift 的 TabBarView 按钮的数组中

creating a new instance of an object and putting it in an array with a button on a TabBarView with swift

我只是想创建一个标签栏视图,上面有一个按钮,用于创建对象的实例,然后将其添加到数组中。我只使用了一个 viewcontroller,但由于某种原因,当我添加一个选项卡栏控制器时,我终其一生都无法让它工作。现在它抛出这个错误 - 致命错误:在展开可选值时意外发现 nil

这是我目前在几个不同文件中的所有代码

class ItemStore {

    var allItems = [Item]()



    @discardableResult func createItem() -> Item {
        let newItem = Item(name: "Item")

        allItems.append(newItem)

        return newItem
    }
}

这就是项目,然后创建并将其添加到数组

这是我的主视图控制器:

class ViewController: UIViewController {

    var itemStore: ItemStore

    required init?() {
    }


    @IBAction func testButton(_ sender: Any) {

        print("This is working")
        itemStore.createItem() //this is where the error gets thrown
        print("We made it")

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        print("is this coming up")


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

这就是我在应用程序委托中所拥有的,让我走到这一步

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var itemStore = ItemStore()


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    let tabController = window?.rootViewController as? ViewController
    tabController?.itemStore = itemStore

    return true
}

我确实有 UITabController 的文件..但它现在是空的。我已经尝试了各种各样的事情,但我想我只是还不明白。

如有任何帮助,我们将不胜感激。

您的 ItemStore 对象似乎已初始化。

在您的 ViewController 中使用以下声明您的 ItemStore :

var itemStore: ItemStore!

当您尝试 强制展开 一个可选变量但值不存在 (nil) 时,会发生上述错误。试试这个方法。


将 itemStore 设为 ViewController

中的可选变量
class ViewController: UIViewController {
    var itemStore: ItemStore?
}

并写下这一行

var itemStore = ItemStore()

里面 didFinishLaunchingWithOptions 修改函数如下

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    var itemStore = ItemStore()

    if let tabController = window?.rootViewController as? ViewController {
      //MAKE SURE THAT THIS `IF` condition is satisfied by putting a break point here
      tabController.itemStore = itemStore
    }


    return true
}

你的函数应该是这样的

@IBAction func testButton(_ sender: Any) {

    guard let itemStore = itemStore else {
     //item store is nil. probably not initialized properly from appDelegate.
     return //be safe
    }
    //itemStore is not nil
    itemStore.createItem() //now error will not be thrown
    print("We made it")

}

如果您需要任何帮助,请告诉我