How Do I Initialize Two Instances of NSObject in the same ViewController - Swift

不想你离开。 提交于 2019-12-09 00:42:37

You ask:

How do I Initialize two instances of NSObject in the same view controller?

Setting aside why you're dealing with NSObject at all (in Objective-C all classes have to subclass from NSObject ultimately, in Swift that's no longer the case), if you want to instantiate two objects, you simply have to have one property for each.

If these are lazily instantiated, as your code snippet suggests, then you have to identify where that lazily instantiated property is referenced (e.g. you might trigger it from a "swipe from edge" gesture) or what have you. Set a breakpoint in the code that references that lazily instantiated property and make sure you're getting there at all.

--

I had some observations on one of your code snippets. You say that you're instantiating your side bar like so:

var sideBar : SideBar?
var ondemandSideBar : SideBar {
    get {
        if sideBar == nil {
            sideBar = SideBar(sourceView, menuItems, menuImage etc.)
            sideBar!.delegate
            SideBar.new()
        }
    }
}

I don't think that's what you're really doing because you're not setting the delegate, you're both instantiating the SideBar as well as calling new (which you shouldn't be doing from Swift), you're not returning a value, etc.

Also, that pattern of having a stored property that is instantiated by some computed property has a certain Objective-C je ne sais quoi. I'm inferring that you want a lazily instantiated property. If that's the case, I'd be inclined to use a single lazy stored property. And I'd then set that property lazily using a closure:

I'd expect something like this pattern

protocol SideBarDelegate : class {                         // specify class so we can use `weak` reference
    func didChooseMenuItem(sender: SideBar, item: Int)
}

class SideBar {
    weak var delegate: SideBarDelegate?                    // make sure this is weak to avoid strong reference cycle
}

class ViewController: UIViewController, SideBarDelegate {

    lazy var sideBar: SideBar = {
        let _sideBar = SideBar(sourceView, menuItems, menuImage, etc.)
        _sideBar.delegate = self
        return _sideBar
    }()

    func didChooseMenuItem(sender: SideBar, item: Int) {
        // handle it here
    }

    // etc.
}

This way, the sideBar won't be instantiated until you reference sideBar somewhere in your code, but when you do, it will be instantiated with the code inside that closure.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!