Last active
March 26, 2019 17:29
-
-
Save eofster/b254c9cc8bd18a0e0455 to your computer and use it in GitHub Desktop.
View controller with property-based dependency injection and abstract factory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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