问题
In my application I want to make it so that when the user opens the application and there are no objects, i want it to add an object to the first section of the table view. I know in my App Delegate in the method:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
I can do something like this:
if (XXXXXX){
NSManagedObjectContext *context = self.managedObjectContext;
NSManagedObject *startingTask = [NSEntityDescription insertNewObjectForEntityForName:@"Tasks" inManagedObjectContext:context];
[startingTask setValue:@"Eat Dinner" forKey:@"taskName"];
[startingTask setValue:[NSNumber numberWithDouble:400] forKey:@"timeInterval"];
[startingTask setValue:@"Tasks To Complete" forKey:@"sectionString"];
}
where XXXXX checks whether the managedobjectcontext is empty (or basically, there are no objects to fetch).
but what would be XXXXX?
回答1:
Just perform the fetch you would normally perform to fill your table. If it returns no records, then the store is empty for your purposes. That's the question you really want to know about.
It's possible that there might be records in the same persistent store that aren't related to your table records, so don't worry about the exact number of total entities in the store for this kind of problem. (Don't assume you model will never change; it's complely legal to put independent entities into a store.)
回答2:
If you mean by empty that the NSManagedObjectContext has no uncommitted changes then you could use this:
- (BOOL)hasChanges
Returns a Boolean value that indicates whether the receiver has uncommitted changes.
Or if you want to reset it so that your sure there are no changes you could use this:
- (void)reset
All the receiver's managed objects are “forgotten.” If you use this method, you should ensure that you also discard references to any managed objects fetched using the receiver, since they will be invalid afterwards.
Ooooorrrr, you could check if all of these are empty (or nil):
- (NSSet *)insertedObjects
The set of objects that have been inserted into the receiver but not yet saved in a persistent store.
- (NSSet *)updatedObjects
The set of objects registered with the receiver that have uncommitted changes.
- (NSSet *)deletedObjects
The set of objects that will be removed from their persistent store during the next save operation.
Cited sources
来源:https://stackoverflow.com/questions/17893134/check-if-managedobjectcontext-is-empty