Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save eofster/b254c9cc8bd18a0e0455 to your computer and use it in GitHub Desktop.
Save eofster/b254c9cc8bd18a0e0455 to your computer and use it in GitHub Desktop.
View controller with property-based dependency injection and abstract factory
import CoreData
import UIKit
struct Photo {}
class PhotoDetailViewController: UIViewController {
var photo: Photo!
var context: NSManagedObjectContext!
}
protocol ViewControllerFactory {
func createPhotoDetailViewControllerWithPhoto(photo: Photo) -> PhotoDetailViewController
}
class StoryboardViewControllerFactory {
let storyboard: UIStoryboard
let context: NSManagedObjectContext
init(storyboard: UIStoryboard, context: NSManagedObjectContext) {
self.storyboard = storyboard
self.context = context
}
}
extension StoryboardViewControllerFactory: ViewControllerFactory {
func createPhotoDetailViewControllerWithPhoto(photo: Photo) -> PhotoDetailViewController {
let vc = storyboard.instantiateViewControllerWithIdentifier("PhotoDetailViewController") as! PhotoDetailViewController
vc.photo = photo
vc.context = context
return vc
}
}
// Usage
let factory: ViewControllerFactory = StoryboardViewControllerFactory(
storyboard: UIStoryboard(name: "Name", bundle: nil),
context: NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
)
let vc = factory.createPhotoDetailViewControllerWithPhoto(Photo())
print(vc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment