سؤال

Recently, I'm working with a timetable app in iOS, and i get trouble with Core Data.

My app has a main user interface kind of like the original calendar app created by Apple, and i save all my events data in the Core Data database.

I create a UIManagedDocument in order to fetch data from database by using its NSManagedObjectContext, and everything works just fine.

However, i need to use the NSManagedObjectContext to fetch data several times in several different view controllers during the runtime. And every time i do this, i need to reopen the UIManagedDocument, but open the document take too much time(it may take 2 seconds or even more, i have to display a spinner in view).

So here are my questions:

  1. What's the right way to open a managedDocument?(I mean like open it during the lunch image time?)
  2. Is there a way to only open the managedDocument once and keep it open during runtime?(So i can use its context all the time)
  3. Does data store in the managedDocument i create?(I found that if i delete the document, data was gone)

Thanks.

هل كانت مفيدة؟

المحلول

You will get lots of different opinions on how to do this but basically you should only have to open the document once. This is done by some object that does the work and stores it so it can return it again when asked by a different view controller.

Many people create singleton's for this or put it in the App Delegate. I have implemented a protocol that lets me put it where ever it is convenient for a particular application without my other code having to know anything about the object that returns the information. As long as it responds to the protocol it can be the App Delegate, a singleton class, or any other object type.

See importing AppDelegate

The protocol that I put in the above example just returns information about where the database is. In my actual implementation I have an openDatabase method with a call back to let me know when it is done plus automatic initialization and updating methods.

You can also improve your performance by having the open operation happen off the main thread. This keeps your UI responsive but does not show the data any faster and you have to be carefull about managed object contexts and the threads they are in.

Good luck...

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top