osx - Right way to define NSManagedObjectContext? -
earlier in apps coredata
used define nsmanagedobjectcontext
way:
class myviewcontroller: nsviewcontroller { lazy var moc: nsmanagedobjectcontext? = { let app = nsapplication.sharedapplication().delegate as! appdelegate if let moc = app.managedobjectcontext { return moc } else { return nil } }() // .... }
but downloaded apple's sample app called eartquakes
, there nsmanagedobjectcontext
that:
import cocoa class coredatastackmanager { class var sharedmanager: coredatastackmanager { struct singleton { static let coredatastackmanager = coredatastackmanager() } return singleton.coredatastackmanager } // persistenstorecoordinator etc...
and in viewcontroller:
class applesviewcontroller: nsviewcontroller { private lazy var managedobjectcontext: nsmanagedobjectcontext = { let moc = nsmanagedobjectcontext(concurrencytype: .mainqueueconcurrencytype) moc.persistentstorecoordinator = coredatastackmanager.sharedmanager.persistentstorecoordinator return moc }() }
so wondering way right way - assume apple's way :) - , why core data stack defined in appdelegate default?
there many ways in end comes maintainability.
the best way have found , goes apple's traditional approach other items is:
- create separate controller core data.
- initialize controller in appdelegate.
- use dependency injection pass controller view controllers.
do not use singleton. while feels easy @ start of project tends paint corner later.
Comments
Post a Comment