I got this work actually
That’s a neat trick. Some comments:
You don’t need to instantiate the derived class; any reference to it will do. Removing that instantiation makes the view controller code much simpler.
If the derived class is referenced by the main storyboard, you need to make sure you ‘touch’ it before
UIApplicationMain
runs.
To test this I first started with an obvious generic view controller.
class BaseViewController<Element>: UITableViewController {
var content: [Element] = []
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.content.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel!.text = "\(self.content[indexPath.row])"
return cell
}
}
I then specialised it for the sake of IB.
class DerivedViewController : BaseViewController<String> {
}
I then set up my main storyboard to reference it and modified
application(_:didFinishLaunchingWithOptions:)
to set it up.
func application(… didFinishLaunchingWithOptions …) -> Bool {
let nav = self.window?.rootViewController! as! UINavigationController
let derived = nav.topViewController! as! DerivedViewController
derived.content = ["Hello", "Cruel", "World"]
return true
}
Finally, I removed @UIApplicationMain from my AppDelegate and replaced it with a
main.swift
as shown below.
import UIKit
print(DerivedViewController.self)
// The following is required because there's an impedence mismatch between
// `CommandLine` and `UIApplicationMain` <rdar://problem/25693546>.
let argv = UnsafeMutableRawPointer(CommandLine.unsafeArgv).bindMemory(
to: UnsafeMutablePointer<Int8>.self,
capacity: Int(CommandLine.argc)
)
UIApplicationMain(CommandLine.argc, argv, nil, NSStringFromClass(AppDelegate.self))
The magic is in line 3, which touches the
DerivedViewController
class and thereby makes it available to the Objective-C runtime. The rest of the stuff is boilerplate, made more difficult by the above-mentioned bug.
Clearly this sort of workaround shouldn’t be necessary. I presumed that folks have filed bugs about this. If you have the bug number handy, please post it, just for my records.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"