Generic controller in swift 2.0 using storyboards

2019-01-17 01:20发布

问题:

Im trying to create a GenericListController for my app.

I have a ProductListController that extend this generic controller which extends UIViewController. I have connected ProductListController to a storyboard and made 2 outlets, but i always receive this error:

 Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIViewController 0x7c158ca0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key searchBar.'

I receive this error for all my outlets, if i remove the generic T from GenericListController it works. I guess a storyboard cant load a super with generics. How can i make it work?

My code:

class GenericListController<T> : UIViewController {

    var list : [T] = [T]()
    var filteredlist : [T] = [T]()

    func getData(tableView : UITableView) {
    .....
    }

    func setData(list : [T], tableView : UITableView) {
    .....
    }

    override func viewDidLoad() {
       super.viewDidLoad()
      }
} 

class ProductListController : GenericListController<ProductModel> {
       @IBOutlet weak var searchBar: UISearchBar!
       @IBOutlet weak var tableView: UITableView!

     override func viewDidLoad() {
       super.viewDidLoad()

       getData(tableView)
     }
}

--EDIT--

I have found that if i extend an generic class and try to add the class to an storyboard xcode wont autocomplete the class name (probably because it cant detect the class)

回答1:

This answers why it is not possible : use a generic class as a custom view in interface builder

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 hint at a possible work around : generics in obj-c Maybe you can create a generic ViewController in obj-c and then IB will accept it?

Have you considered using a protocol? This doesn't upset the storyboard. Changed the code a bit to make it easily testable. The downside of this is that you can't have stored properties in a protocol. So you would still need to copy paste those. Upside is that it works.

protocol GenericListProtocol {       
    typealias T
    var list : [T] { get set }
    var filteredlist : [T] { get set }
    func setData(list : [T])        
}    
extension GenericListProtocol {        
    func setData(list: [T]) {
        list.forEach { item in print(item) }
    }        
}

class ProductModel {        
    var productID : Int = 0        
    init(id:Int) {
        productID = id
    }        
}    

class ProductListController: UIViewController, GenericListProtocol {

    var list : [ProductModel] = [ProductModel(id: 1),ProductModel(id: 2),ProductModel(id: 3),ProductModel(id: 4)]
    var filteredlist : [ProductModel] = []

    override func viewDidLoad() {            
        super.viewDidLoad()            
        setData(list)            
    }
}

Update: Allow some access to attributes to the generic class. Changed it to a basic class to easily test in a Playground. UIViewController stuff is in the code above.

class ProductModel {        
    var productID : Int = 0        
    init(id:Int) {
        productID = id
    }        
}

class ProductA : ProductModel {
    var aSpecificStuff : Float = 0
}    

class ProductB : ProductModel {
    var bSpecificStuff : String = ""
}

protocol GenericListProtocol {        
    typealias T = ProductModel
    var list : [T] { get set }
    var filteredlist : [T] { get set }
    func setData(list : [T])        
}

extension GenericListProtocol {        
    func setData(list: [T]) {
        list.forEach { item in
            guard let productItem = item as? ProductModel else {
                return
            }
            print(productItem.productID)
        }
    }        
}


class ProductListController: GenericListProtocol {

    var list : [ProductA] = [ProductA(id: 1),ProductA(id: 2),ProductA(id: 3),ProductA(id: 4)]
    var filteredlist : [ProductA] = []

    init() {            
        setData(list)            
    }
}

var test = ProductListController()


回答2:

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<T> {}
class D: C<String> {}

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<T> {}
class D: C<String> {}

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<SomeGeneric1, SomeGeneric2>

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.



回答3:

Ill post some code i have archieved with help from user R menke and others. My goal is to have a GenericListProtocol that can handle UISearchBarDelegate, UITableViewDelegate and my getData method (which needs a type class to be able to correctly parse json.

import Foundation
import UIKit

protocol GenericListProtocol : UISearchBarDelegate, UITableViewDelegate{
    typealias T : MyModel // MyModel is a model i use for getId, getDate...
    var list : [T] { get set }
    var filteredlist : [T] { get set }

    var searchActive : Bool { get set }

    func setData(tableView : UITableView, myList : [T])

    func setData()

    func getData(tableView : UITableView, objectType : T, var myList : [T])

    func filterContentForSearchText(searchText: String)

}

extension GenericListProtocol {

  func setData(atableView : UITableView, myList : [T]) {
    print("reloading tableView data")
    atableView.reloadData()
  }

  func getData(tableView : UITableView, objectType : T, var myList : [T]) {

    let dao: GenericDao<T> = GenericDao<T>()
    let view : UIView = UIView()

    let c: CallListListener<T> = CallListListener<T>(view: view, loadingLabel: "loading", save: true, name: "ProductModel")

    c.onSuccess = { (onSuccess: JsonMessageList<T>) in
        print("status " + onSuccess._meta!.status!) // this is from my ws

        myList = onSuccess.records

        self.setData(tableView, myList: myList)
    }

    c.onFinally = { (any: AnyObject) in
      //  tableView.stopPullToRefresh()
    }

   // my dao saves json list on NSUSER, so we check if its already downloaded 
    let savedList = c.getDefaultList()
    if (savedList == nil) {
        dao.getAll(c);
    }
    else {
         myList = savedList!
        print(String(myList.count))
        self.setData(tableView, myList: myList)

    }


  }

  func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    searchActive = true;
  }

  func searchBarTextDidEndEditing(searchBar: UISearchBar) {
    searchActive = false;
  }

  func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    searchActive = false;
  }

  func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    searchActive = false;
  }

  func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    print("searching")
    self.filterContentForSearchText(searchText)
    if(filteredlist.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }
     self.setData()
  }



}

Although i was able to implement most UISearchBarDelegate, UITableViewDelegate methods, i still have to implement 2 of them on my default class:

import Foundation
import UIKit
import EVReflection
import AlamofireJsonToObjects

class ProductListController : GenericListController, GenericListProtocol { 

  @IBOutlet weak var searchBar: UISearchBar!
  @IBOutlet weak var tableView: UITableView!


  var list : [ProductModel] = [ProductModel]()
  var filteredlist : [ProductModel] = [ProductModel]()
  var searchActive : Bool = false


   override func setInit() {
    self.searchBar.delegate = self
    self.listName = "ProductModel"
    self.setTableViewStyle(self.tableView, searchBar4 : self.searchBar)
    getData(self.tableView, objectType: ProductModel(), myList: self.list)
  }

  // this method hasnt worked from extension, so i just pasted it here
  func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

    self.filterContentForSearchText(searchText)
    if(filteredlist.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }
    self.setData(self.tableView, myList: list)
  }

  // this method hasnt worked from extension, so i just pasted it here
  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if searchActive {
        return self.filteredlist.count
    } else {
        return self.list.count
    }
  }

  // self.list = myList hasnt worked from extension, so i just pasted it here
  func setData(atableView: UITableView, myList : [ProductModel]) {
    print(String(myList.count))
    self.list = myList
    print(String(self.list.count))
    self.tableView.reloadData()
  }

  // i decided to implement this method because of the tableView
  func setData() {
    self.tableView.reloadData()
  }


  // this method hasnt worked from extension, so i just pasted it here
  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell:GenericListCell = tableView.dequeueReusableCellWithIdentifier("cell") as! GenericListCell


    var object : ProductModel
    if searchActive {
        object = filteredlist[indexPath.row]
    } else {
        object = list[indexPath.row]
    }

    cell.formatData(object.name!, subtitle: object.price ?? "valor", char: object.name!)
    print("returning cell")


    return cell

  }


  override func viewDidLoad() {
   //         searchFuckinBar.delegate = self
    super.viewDidLoad()


    // Do any additional setup after loading the view, typically from a nib.
  }


   func filterContentForSearchText(searchText: String) {
    // Filter the array using the filter method
    self.filteredlist = self.list.filter({( object: ProductModel) -> Bool in
        // let categoryMatch = (scope == "All") || (object.category == scope)
        let stringMatch = object.name!.lowercaseString.rangeOfString(searchText.lowercaseString)
        return  (stringMatch != nil)
    })
  }

    func formatCell(cell : GenericListCell, object : ProductModel) {
    cell.formatData(object.name!, subtitle: object.price ?? "valor", char: object.name!)
  }

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

*GenericListController is just a UIViewController with some helper methods



回答4:

As a workaround you could just load your ProductListController into the ObjC runtime(i.e. AppDelegate?) before instantiating it with the Storyboard.

ProductListController.load()

Cheers