3 回答
TA贡献1911条经验 获得超7个赞
iOS 9及更高版本:
iOS 9添加了一个名为的新类NSBatchDeleteRequest,它允许您轻松删除与谓词匹配的对象,而无需将它们全部加载到内存中。这是你如何使用它:
斯威夫特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];
有关批量删除的更多信息可以在WWDC 2015的“核心数据中的新内容”会话中找到(从~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条经验 获得超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条经验 获得超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 关注
- 550 浏览
添加回答
举报