Skip to content

Instantly share code, notes, and snippets.

  • Save vukcevich/bc6bbe281f3a43d470207511a2f76862 to your computer and use it in GitHub Desktop.
Save vukcevich/bc6bbe281f3a43d470207511a2f76862 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