When a UIManagedDocument instance is opened (document state is normal?), how to check if a UIManagedDocument is empty? By “empty” here means no entity in the document at all.
Or could I just check the emptiness when it is still closed?
if (self.photoDatabase.documentState == UIDocumentStateClosed)
{
[self.photoDatabase openWithCompletionHandler:^(BOOL success) {}];
[self setupFetchedResultsController];
if ( // check if document is empty )
{
[self fetchFlickrDatatoDocument:self.photoDatabase];
}
}
Several answers here…
First, the document is surely empty wen you create it. You can just query the file system to see if the file exists.
If it remains empty, why did you create it in the first place?
If you are in the habit of opening empty database files, then you can tell if it is “empty” in a number of ways, depending on what “empty” means.
Perform a fetch to get the count of records. If it returns 0, the database is empty.
Perform a fetch for a “special” entity that keeps meta data about the database. If it is not there, then the database is empty.
EDIT
To check and see if there are no entities, just ask for the count…
Or, you can just fetch one entity…
EDIT
Sorry, Philip, but that last comment does not make sense to me. How is asking the database to tell me how many items it has of a certain entity type assuming that it has any at all.
It’s like the kid’s card game:
Me: Yo, database, you got any fours?
CoreData: Go fish.
Now, my best guess at your comment is that you are confusing database model with database records.
When you create the database, you gave it a model. Did you create the model with the GUI, or in code? Either way, you have already told the database the types of entities it will contain, and the relationships between them.
When you initially create the database, it already knows about all the entities (that’s what the managed object model is all about). The core-data managed object context needs a persistent store, which needs a managed object model.
Thus, when the core data stack is completely instantiated, it has all the knowledge it needs about what types of entities will be in the database.