Generic controller in swift 2.0 using storyboards

后端 未结 4 1764
名媛妹妹
名媛妹妹 2020-12-08 04:35

Im trying to create a GenericListController for my app.

I have a ProductListController that extend this generic controller which extends UIViewController. I have

4条回答
  •  伪装坚强ぢ
    2020-12-08 05:37

    As @r-menke stated above:

    Interface Builder "talks" to your code through the ObjC runtime. As such, IB can can access only features of your code that are representable in the ObjC runtime. ObjC doesn't do generics

    This is true,

    In my experience, however, we can get around the issue as follows (YMMV).

    We can make a contrived example here and see how this fails:

    class C {}
    class D: C {}
    
    print(NSClassFromString("main.D"))
    

    Running example here:

    http://swiftstub.com/878703680

    You can see that it prints nil

    Now lets tweak this slightly and try again:

    http://swiftstub.com/346544378

    class C {}
    class D: C {}
    
    print(NSClassFromString("main.D"))
    let _ = D()
    print(NSClassFromString("main.D"))
    

    We get this:

    nil Optional(main.D)

    Hey-o! It found it AFTER it was initialized the first time.

    Lets apply this to storyboards. I am doing this in an application right now (rightly or wrongly)

    // do the initial throw away load
    let _ = CanvasController(nibName: "", bundle: nil)
    
    // Now lets load the storyboard
    let sb = NSStoryboard(name: "Canvas", bundle: nil)
    let canvas = sb.instantiateInitialController() as! CanvasController
    
    myView.addSubView(canvas.view)
    

    Works as you would expect. In my case my CanvasController is declared as follows:

    class CanvasController: MyNSViewController
    

    Now, I have run into some issues on iOS using this technique with a generic UITableView subclass. I have not tried it under iOS 9 so YMMV. But I am currently doing this under 10.11 for an app I am working on, and have not run into any major issues. That is not to say that I won't run into any issue in the future, or that this is even appropriate to do I cannot claim to know the full ramifications of this. All I can say is that, for now, it appears to get around the issue.

    I filed a radr on this back on Aug 4: #22133133 I don't see it in open RADR, but under bugreport.apple.com it's at least listed under my account, whatever that's worth.

提交回复
热议问题