0

I want to access to CoreData without UIApplication.sharedApplication() because I want to manage CoreData from Extension and Application. For example I don't want to use:

var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!

But use something without UIApplication...

Thank you !

martinpristas
  • 489
  • 5
  • 12
  • An extension of your app delegate? – Ian Nov 14 '14 at 18:31
  • I mean Today Extension ... I want to access to core data from ViewController of my application and also from TodayViewController... – martinpristas Nov 14 '14 at 18:32
  • You set it up in your app delegate then you access it from whatever view controller you want. Create a new project and select "use core data" then check the code in the app delegate. It's the best place to store that code because it has "applicationDidTerminate" and other methods that are called only in the app delegate which are great places to save the managed object context – Ian Nov 14 '14 at 18:41
  • I know this , nut I need that code in swift to acces to Core Data.. Like function for example ... – martinpristas Nov 14 '14 at 19:01
  • Not entirely sure if this a duplicate because it is in Objective-C, but this is how it works: http://stackoverflow.com/questions/21050408/how-to-get-managedobjectcontext-for-viewcontroller-other-than-getting-it-from-ap/21050881#21050881 You should be able to translate that to Swift, Dependency Injection is a very simple concept with a fancy name. – Matthias Bauch Nov 14 '14 at 20:58
  • hmm not helpfully at all, I really need some real function .. I'm noob at iOS, just learning :-/ ... – martinpristas Nov 14 '14 at 21:37
  • This is also pretty much a duplicate question from: http://stackoverflow.com/questions/28398952/read-coredata-in-today-widget-in-swift-or-objective-c/28399010#comment45134322_28399010 – TheCodingArt Feb 08 '15 at 21:05

1 Answers1

2

I would simply make it so that the App Delegate doesn't own the managed object context. I know that the auto generated core data code does this, but I feel like its bad form to marry core data to your app delegate.

InkGolem
  • 2,662
  • 1
  • 15
  • 22
  • Agreed with the above. It's good to setup a CoreData stack in a separate object and or pass around a manageObjectContext to viewControllers so different parts of the application can use/branch off of these to their will. The default code is simply template code, it doesn't mean you have to use it as is. – TheCodingArt Feb 08 '15 at 21:03