Return to Snippet

Revision: 54305
at December 19, 2011 21:29 by mirage3d


Initial Code
- (BOOL)clearEntity:(NSString *)entity
    NSManagedObjectContext *myContext = [(<#YourAppDelegate#> *)[[NSApplication sharedApplication] delegate] managedObjecContext];
    NSFetchRequest *fetchLLObjects = [[NSFetchRequest alloc] init];
    [fetchAllObjects setEntity:[NSEntityDescription entityForName:entity inManagedObjectContext:myContext]];
    [fetchAllObjects setIncludesPropertyValues:NO]; //only fetch the managedObjectID

    NSError *error = nil;
    NSArray *allObjects = [myContext executeFetchRequest:fetchAllObjects error:&error];
    // uncomment next line if you're NOT using ARC
    // [allObjects release];
    if (error) {
        [[NSApplication sharedApplication] presentError:error];
    }

    for (NSManagedObject *object in allObjects) {
        [myContext deleteObject:object];
    }

    NSError *saveError = nil;
    if (![myContext save:&saveError]) {
        [[NSApplication sharedApplication] presentError:error];
    }

    return (saveError == nil);
}

Initial URL
http://stackoverflow.com/a/1383645/215494

Initial Description
How do you delete all objects in an entity in Core Data? It's not as simple or straightforward as it is in SQL/SQLite. here's one reasonably quick way...

taken from stackoverflow

Initial Title
Clear all objects from an entity

Initial Tags
mac

Initial Language
Objective C