3 回答

TA貢獻1911條經(jīng)驗 獲得超7個贊
iOS 9及更高版本:
iOS 9添加了一個名為的新類NSBatchDeleteRequest,它允許您輕松刪除與謂詞匹配的對象,而無需將它們?nèi)考虞d到內(nèi)存中。這是你如何使用它:
斯威夫特2
let fetchRequest = NSFetchRequest(entityName: "Car")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try myPersistentStoreCoordinator.executeRequest(deleteRequest, withContext: myContext)
} catch let error as NSError {
// TODO: handle the error
}
Objective-C的
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Car"];
NSBatchDeleteRequest *delete = [[NSBatchDeleteRequest alloc] initWithFetchRequest:request];
NSError *deleteError = nil;
[myPersistentStoreCoordinator executeRequest:delete withContext:myContext error:&deleteError];
有關(guān)批量刪除的更多信息可以在WWDC 2015的“核心數(shù)據(jù)中的新內(nèi)容”會話中找到(從~14:10開始)。
iOS 8及更早版本:
獲取所有并刪除所有:
NSFetchRequest *allCars = [[NSFetchRequest alloc] init];
[allCars setEntity:[NSEntityDescription entityForName:@"Car" inManagedObjectContext:myContext]];
[allCars setIncludesPropertyValues:NO]; //only fetch the managedObjectID
NSError *error = nil;
NSArray *cars = [myContext executeFetchRequest:allCars error:&error];
[allCars release];
//error handling goes here
for (NSManagedObject *car in cars) {
[myContext deleteObject:car];
}
NSError *saveError = nil;
[myContext save:&saveError];
//more error handling here

TA貢獻1859條經(jīng)驗 獲得超6個贊
更清潔和通用:添加此方法:
- (void)deleteAllEntities:(NSString *)nameEntity{ NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:nameEntity]; [fetchRequest setIncludesPropertyValues:NO]; //only fetch the managedObjectID NSError *error; NSArray *fetchedObjects = [theContext executeFetchRequest:fetchRequest error:&error]; for (NSManagedObject *object in fetchedObjects) { [theContext deleteObject:object]; } error = nil; [theContext save:&error];}

TA貢獻1786條經(jīng)驗 獲得超11個贊
在Swift 3中重置實體:
func resetAllRecords(in entity : String) // entity = Your_Entity_Name { let context = ( UIApplication.shared.delegate as! AppDelegate ).persistentContainer.viewContext let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: entity) let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch) do { try context.execute(deleteRequest) try context.save() } catch { print ("There was an error") } }
- 3 回答
- 0 關(guān)注
- 590 瀏覽
添加回答
舉報