문제

Core Data에 저장된 모든 항목을 삭제하는 방법을 알고 있습니까?내 스키마는 동일하게 유지되어야 합니다.그냥 공백으로 재설정하고 싶습니다.


편집하다

나는 사용자가 본질적으로 reset 단추.

도움이 되었습니까?

해결책

nsfileManager : removeItematpath :: method를 사용하여 프로그래밍 방식으로 파일을 삭제할 수 있습니다.

NSPersistentStore *store = ...;
NSError *error;
NSURL *storeURL = store.URL;
NSPersistentStoreCoordinator *storeCoordinator = ...;
[storeCoordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];

그런 다음 영구 상점을 다시 추가하여 제대로 재현되도록하십시오.

각 엔티티를 반복하는 프로그래밍 방식은 느리고 오류가 발생하기 쉽습니다. 그런 식으로 수행하는 데 사용하는 것은 다른 엔티티가 아닌 일부 엔티티를 삭제하려는 경우입니다. 그러나 여전히 참조 무결성을 유지하거나 변경 사항을 지속 할 수 없도록해야합니다.

매장을 제거하고 재현하는 것만으로는 빠르고 안전하며 런타임에 프로그램적으로 수행 할 수 있습니다.

iOS5+에 대한 업데이트

iOS 5 및 OS X 10.7에서 외부 바이너리 스토리지 (allowSexternalbinaryDatastorage 또는 외부 레코드 파일에 저장)가 도입되면 StoreUrls가 가리키는 파일로 간단히 삭제하면 충분하지 않습니다. 외부 레코드 파일을 남겨 두십시오. 이러한 외부 레코드 파일의 이름 지정 체계는 공개적이지 않기 때문에 아직 보편적 인 솔루션이 없습니다. - AN0 5 월 8 '12 at 23:00

다른 팁

sqlite 파일을 삭제할 수 있지만 기능으로 테이블을 개별적으로 제거하여 다음을 선택합니다.

- (void) deleteAllObjects: (NSString *) entityDescription  {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityDescription inManagedObjectContext:_managedObjectContext];
    [fetchRequest setEntity:entity];

    NSError *error;
    NSArray *items = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];
    [fetchRequest release];


    for (NSManagedObject *managedObject in items) {
        [_managedObjectContext deleteObject:managedObject];
        DLog(@"%@ object deleted",entityDescription);
    }
    if (![_managedObjectContext save:&error]) {
        DLog(@"Error deleting %@ - error:%@",entityDescription,error);
    }

}

내가 테이블로 그것을 선택한 이유는 테이블의 내용을 삭제하는 것이 합리적이며 오히려 유지하려는 데이터가 없다는 프로그래밍을 수행 할 때 확인할 수 있기 때문입니다.

이 작업을 수행하면 파일을 삭제하는 것보다 훨씬 느립니다.이 메소드가 너무 오래 걸리면 파일 삭제로 변경합니다.

iOS 10+에 대한 업데이트 된 솔루션

사용 NSBatchDeleteRequest 엔티티의 모든 객체를 메모리에로드하거나 반복하지 않고도 엔티티의 모든 객체를 삭제합니다.

// create the delete request for the specified entity
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = MyEntity.fetchRequest()
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

// get reference to the persistent container
let persistentContainer = (UIApplication.shared.delegate as! AppDelegate).persistentContainer

// perform the delete
do {
    try persistentContainer.viewContext.execute(deleteRequest)
} catch let error as NSError {
    print(error)
}

이 코드는 iOS 10 및 Swift 3에 대해 업데이트되었습니다. iOS 9를 지원 해야하는 경우 참조하십시오. 이 질문.

출처 :

나는 a clearStores 모든 상점을 통해 진행되는 방법으로 코디네이터와 파일 시스템 모두에서 삭제하는 방법 (오류 처리가 남은 오류) :

NSArray *stores = [persistentStoreCoordinator persistentStores];

for(NSPersistentStore *store in stores) {
    [persistentStoreCoordinator removePersistentStore:store error:nil];
    [[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:nil];
}

[persistentStoreCoordinator release], persistentStoreCoordinator = nil;

이 방법은 a 내부에 있습니다 coreDataHelper (무엇보다도)를 돌보는 클래스는 nil 일 때 지속원을 만들어냅니다.

HomeViewController 클래스의 버튼 이벤트의 핵심 데이터에서 모든 데이터를 제거했습니다.이 기사는 기여할 것이라고 생각했습니다.

-(IBAction)buttonReset:(id)sender
{
    NSLog(@"buttonReset Pressed");

    //Erase the persistent store from coordinator and also file manager.
    NSPersistentStore *store = [self.persistentStoreCoordinator.persistentStores lastObject];
    NSError *error = nil;
    NSURL *storeURL = store.URL;
    [self.persistentStoreCoordinator removePersistentStore:store error:&error];
    [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];


    NSLog(@"Data Reset");

    //Make new persistent store for future saves   (Taken From Above Answer)
    if (![self.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // do something with the error
    }

}

Self.PersistentStoreCoordinator를 호출하려면 Home View Controller에 속성을 선언했습니다. (저장 및로드에 사용하는 ManagedObjectContext에 대해 걱정하지 마십시오.)

@property (nonatomic, retain) NSManagedObjectContext        *   managedObjectContext;
@property (nonatomic, retain) NSPersistentStoreCoordinator  *   persistentStoreCoordinator;

그런 다음 appdelegate application didfinishlaunching 바로 아래에서 홈 뷰 콘트롤러를 만듭니다.

homeViewController = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
homeViewController.managedObjectContext = self.managedObjectContext;
homeViewController.persistentStoreCoordinator = self.persistentStoreCoordinator;

MagicalRecord 이것을 매우 쉽게 만듭니다.

[MyCoreDataObject MR_truncateAll];

iOS9+, 스위프트 2

모든 엔티티의 모든 객체를 삭제합니다

func clearCoreDataStore() {
    let entities = managedObjectModel.entities
    for entity in entities {
        let fetchRequest = NSFetchRequest(entityName: entity.name!)
        let deleteReqest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        do {
            try context.executeRequest(deleteReqest)
        } catch {
            print(error)
        }
    }
}

[새로운 응답을 요구하는 포상금에 대한 답변이 늦었습니다.]

이전 답변을 살펴보면,

  • @Grouchal 및 기타 사람들이 제안한 대로 모든 항목을 가져오고 삭제하는 것은 여전히 ​​효과적이고 유용한 솔루션입니다.매우 큰 데이터 저장소가 있는 경우 속도가 느려질 수 있지만 여전히 잘 작동합니다.
  • 귀하와 @groundhog가 지적했듯이 단순히 데이터 저장소를 제거하는 것은 더 이상 효과적이지 않습니다.구식이야 외부 바이너리 저장소를 사용하지 않더라도 iOS 7은 SQLite 저널링에 WAL 모드를 사용하기 때문입니다.WAL 모드를 사용하면 Core Data 영구 저장소에 (잠재적으로 큰) 저널 파일이 있을 수 있습니다.

그러나 작동하는 영구 저장소를 제거하는 다른 유사한 접근 방식이 있습니다.핵심은 다른 어떤 것도 포함하지 않는 자체 하위 디렉터리에 영구 저장소 파일을 저장하는 것입니다.문서 디렉터리(또는 다른 곳)에 그냥 두지 말고 영구 저장소를 위한 새 하위 디렉터리를 만드세요.해당 디렉터리의 내용은 결국 영구 저장소 파일, 저널 파일 및 외부 바이너리 파일이 됩니다.전체 데이터 저장소를 핵폭탄으로 만들려면 해당 디렉터리를 삭제하면 모두 사라집니다.

영구 저장소를 설정할 때 다음과 같은 작업을 수행합니다.

NSURL *storeDirectoryURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"persistent-store"];
if ([[NSFileManager defaultManager] createDirectoryAtURL:storeDirectoryURL
        withIntermediateDirectories:NO
        attributes:nil
        error:nil]) {
    NSURL *storeURL = [storeDirectoryURL URLByAppendingPathComponent:@"MyApp.sqlite"];
    // continue with storeURL as usual...
}

그런 다음 저장소를 제거하고 싶을 때

[[NSFileManager defaultManager] removeItemAtURL:storeDirectoryURL error:nil];

그러면 사용자 정의 하위 디렉터리와 그 안에 있는 모든 핵심 데이터 파일이 모두 반복적으로 제거됩니다.

이는 다른 중요한 데이터와 동일한 폴더에 영구 저장소가 아직 없는 경우에만 작동합니다..다른 유용한 내용이 들어 있는 문서 디렉토리와 같습니다.이것이 귀하의 상황이라면, 원하는 파일을 찾아도 동일한 효과를 얻을 수 있습니다. 하다 다른 모든 것을 유지하고 제거하고 싶습니다.다음과 같은 것 :

NSString *docsDirectoryPath = [[self applicationDocumentsDirectory] path];
NSArray *docsDirectoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:docsDirectoryPath error:nil];
for (NSString *docsDirectoryItem in docsDirectoryContents) {
    // Look at docsDirectoryItem. If it's something you want to keep, do nothing.
    // If it's something you don't recognize, remove it.
}

이 접근 방식은 오류가 발생하기 쉬울 수 있습니다..당신은 당신이 알고 있다는 것을 절대적으로 확신해야합니다 모든 그렇지 않으면 중요한 데이터가 제거될 수 있기 때문입니다.반면, 외부 바이너리 파일을 저장하는 데 사용된 파일/디렉터리 이름을 실제로 알지 못해도 외부 바이너리 파일을 제거할 수 있습니다.

모든 객체를 삭제하려고하고 후원 파일을 삭제하려면 다음 방법을 사용할 수 있습니다.

- (void)deleteAllObjectsInContext:(NSManagedObjectContext *)context
                       usingModel:(NSManagedObjectModel *)model
{
    NSArray *entities = model.entities;
    for (NSEntityDescription *entityDescription in entities) {
        [self deleteAllObjectsWithEntityName:entityDescription.name
                                   inContext:context];
    }
}

- (void)deleteAllObjectsWithEntityName:(NSString *)entityName
                             inContext:(NSManagedObjectContext *)context
{
    NSFetchRequest *fetchRequest =
        [NSFetchRequest fetchRequestWithEntityName:entityName];
    fetchRequest.includesPropertyValues = NO;
    fetchRequest.includesSubentities = NO;

    NSError *error;
    NSArray *items = [context executeFetchRequest:fetchRequest error:&error];

    for (NSManagedObject *managedObject in items) {
        [context deleteObject:managedObject];
        NSLog(@"Deleted %@", entityName);
    }
}

매우 느릴 수 있음을주의하십시오 (객체 그래프에 몇 개의 개체가 있는지에 따라 다름).

다음은 코어 데이터를 제거하기위한 결합 된 솔루션입니다.

- (void)deleteAllObjectsInCoreData
{
    NSArray *allEntities = self.managedObjectModel.entities;
    for (NSEntityDescription *entityDescription in allEntities)
    {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        [fetchRequest setEntity:entityDescription];

        fetchRequest.includesPropertyValues = NO;
        fetchRequest.includesSubentities = NO;

        NSError *error;
        NSArray *items = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

        if (error) {
                NSLog(@"Error requesting items from Core Data: %@", [error localizedDescription]);
            }

        for (NSManagedObject *managedObject in items) {
            [self.managedObjectContext deleteObject:managedObject];
        }

        if (![self.managedObjectContext save:&error]) {
            NSLog(@"Error deleting %@ - error:%@", entityDescription, [error localizedDescription]);
        }
    }  
}

모든 객체 삭제 경로로 이동하려면 (핵심 데이터 스택을 찢어내는 것보다 훨씬 간단하지만) 더 나은 구현입니다.

- (void)deleteAllManagedObjectsInModel:(NSManagedObjectModel *)managedObjectModel context:(NSManagedObjectContext *)managedObjectContext
{
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        [managedObjectContext performBlockAndWait:^{
            for (NSEntityDescription *entity in managedObjectModel) {
                NSFetchRequest *fetchRequest = [NSFetchRequest new];
                [fetchRequest setEntity:entity];
                [fetchRequest setIncludesSubentities:NO];
                NSArray *objects = [managedObjectContext executeFetchRequest:fetchRequest error:nil];
                for (NSManagedObject *managedObject in objects) {
                    [managedObjectContext deleteObject:managedObject];
                }            
            }

            [managedObjectContext save:nil];
        }];
    }];
    [operation setCompletionBlock:^{
        // Do stuff once the truncation is complete
    }];
    [operation start];
}

이 구현은 활용됩니다 NSOperation 기본 스레드에서 삭제를 수행하고 완료시 알림을 받으십시오. 완료 블록 내에 알림이나 무언가를 주 스레드로 다시 거품으로 만들 수 있습니다.

iOS 10 + Swift 3 솔루션 :

func clearCoreDataStore() {
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext

    for i in 0...delegate.persistentContainer.managedObjectModel.entities.count-1 {
        let entity = delegate.persistentContainer.managedObjectModel.entities[i]

        do {
            let query = NSFetchRequest<NSFetchRequestResult>(entityName: entity.name!)
            let deleterequest = NSBatchDeleteRequest(fetchRequest: query)
            try context.execute(deleterequest)
            try context.save()

        } catch let error as NSError {
            print("Error: \(error.localizedDescription)")
            abort()
        }
    }
}

모든 핵심 데이터 엔티티를 반복하여이를 지우겠습니다.

다음은 AppDelegate Self에 대한 호출이 적고 최고 등급의 답변에서 제외 된 마지막 코드가있는 다소 단순화 된 버전입니다. 또한이 NSmanagedObjectContext의 코디네이터에서 "Object의 영구 상점은 도달 할 수 없습니다"오류가 발생했습니다. "

NSPersistentStoreCoordinator *storeCoordinator = [self persistentStoreCoordinator];
NSPersistentStore *store = [[storeCoordinator persistentStores] lastObject];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"dataModel"];
NSError *error;

[storeCoordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];

[_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];

if (storeCoordinator != nil) {
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:storeCoordinator];
}

스위프트 솔루션 :

class func deleteAllManagedObjects() {

        let modelURL = NSBundle.mainBundle().URLForResource("some string", withExtension: "mom")
        let mom = NSManagedObjectModel(contentsOfURL: modelURL)

        for entityName in mom.entitiesByName.keys {
            let fr = NSFetchRequest(entityName: entityName as String)
            let a = Utility.managedObjectContext().executeFetchRequest(fr, error: nil) as [NSManagedObject]
            for mo in a {
                Utility.managedObjectContext().deleteObject(mo)
            }
        }

        Utility.managedObjectContext().save(nil)
    }

다른 곳에서 검색 저장에 대한 빠른 참조로 - 삭제 한 후 지속적인 매장을 재현하는 것 : 다음과 같이 수행 할 수 있습니다.

if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// do something with the error
}

게시물에 감사드립니다. 나는 그것을 따랐고 그것은 나를 위해 일했다. 그러나 나는 어떤 답장에 언급되지 않은 또 다른 문제가있었습니다. 그래서 나는 그것이 단지 나인지 확실하지 않습니다.

어쨌든, 나는 여기에 문제와 그것을 해결하는 방법을 게시 할 것이라고 생각했습니다.

데이터베이스에 몇 가지 레코드가 있었는데 DB에 새 데이터를 작성하기 전에 모든 것을 깨끗하게 제거하고 싶었으므로 다음을 포함하여 모든 것을 수행했습니다.

[[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error]; 

그리고 사용했습니다 managedObjectContext 데이터베이스에 액세스하기 위해 (지금까지 비어 있어야 함)는 어떻게 든 데이터가 여전히 존재했습니다. 문제 해결 후 잠시 후 재설정해야한다는 것을 알았습니다. managedObjectContext, managedObject, managedObjectModel 그리고persistentStoreCoordinator, 내가 사용하기 전에 managedObjectContext Dabase에 액세스하려면. 이제 쓸 수있는 깨끗한 데이터베이스가 있습니다.

이 질문에 대한 몇 가지 좋은 답변. 여기에 좋은 간결한 것이 있습니다. 처음 두 줄은 sqlite 데이터베이스를 삭제합니다. 그런 다음 or : 루프는 managedObjectContext 메모리에서 모든 객체를 삭제합니다.

NSURL *storeURL = [[(FXYAppDelegate*)[[UIApplication sharedApplication] delegate] applicationDocumentsDirectory] URLByAppendingPathComponent:@"AppName.sqlite"];
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil];
for (NSManagedObject *ct in [self.managedObjectContext registeredObjects]) {
    [self.managedObjectContext deleteObject:ct];
}

모든 엔티티 이름을 찾아 이름으로 삭제할 수도 있습니다. 더 긴 버전이지만 잘 작동합니다. 그렇게하면 Persistence Store와 함께 일할 필요가 없습니다.

 - (void)clearCoreData
{
NSError *error;
NSEntityDescription *des = [NSEntityDescription entityForName:@"Any_Entity_Name" inManagedObjectContext:_managedObjectContext];
NSManagedObjectModel *model = [des managedObjectModel];
NSArray *entityNames = [[model entities] valueForKey:@"name"];

for (NSString *entityName in entityNames){

    NSFetchRequest *deleteAll = [NSFetchRequest fetchRequestWithEntityName:entityName];
    NSArray *matches = [self.database.managedObjectContext executeFetchRequest:deleteAll error:&error];

}
    if (matches.count > 0){
        for (id obj in matches){

            [_managedObjectContext deleteObject:obj];
        }
       [self.database.managedObjectContext save:&error];
    }
}

"any_entity_name"의 경우 엔티티 이름 중 하나만 제공하면 엔티티가 내부에있는 엔티티 설명 만 파악하면됩니다. ValueForKey@"이름"은 모든 엔티티 이름을 반환합니다. 마지막으로 저장하는 것을 잊지 마십시오.

NSFILEMANAGER의 URL을 제거하면 허용 된 답변이 정확하지만 iOS 5+ 편집에 명시된 바와 같이 영구 저장소는 하나의 파일 만 표시되지 않습니다. sqlite 매장의 경우 *.sqlite, *.sqlite-shm 및 *.sqlite-wal ... 다행히 iOS 7+ 이후로 우리는 방법을 사용할 수 있습니다.

nspersistentStoreCoordinator +removeUbiquitousContentandPersistentStoreatUrl : 옵션 : 오류 :

제거를 처리하려면 코드가 다음과 같아야합니다.

NSPersistentStore *store = ...;
NSError *error;
NSURL *storeURL = store.URL;
NSString *storeName = ...;
NSPersistentStoreCoordinator *storeCoordinator = ...;
[storeCoordinator removePersistentStore:store error:&error];
[NSPersistentStoreCoordinator removeUbiquitousContentAndPersistentStoreAtURL:storeURL.path options:@{NSPersistentStoreUbiquitousContentNameKey: storeName} error:&error];

모든 버전과 함께 작동합니다. 엔티티 이름을 전달하고 반복하여 모든 항목을 삭제하고 컨텍스트를 저장하십시오.

func deleteData(entityToFetch: String, completion: @escaping(_ returned: Bool) ->()) {
    var context = NSManagedObjectContext()
    if #available(iOS 10.0, *) {
        context = self.persistentContainer.viewContext
    } else {
        context = self.managedObjectContext
    }

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
    fetchRequest.entity = NSEntityDescription.entity(forEntityName: entityToFetch, in: context)
    fetchRequest.includesPropertyValues = false
    do {
        let results = try context.fetch(fetchRequest) as! [NSManagedObject]
        for result in results {
            context.delete(result)
        }
        try context.save()
        completion(true)
    } catch {
        completion(false)
        print("fetch error -\(error.localizedDescription)")
    }
}

다음은 모든 테이블의 모든 레코드를 삭제하는 버전입니다.

스위프트 4

static func resetDatabase() {
    do {
        try dataStore.persistentStoreCoordinator.managedObjectModel.entities.forEach { (entity) in
            if let name = entity.name {
                let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: name)
                let request = NSBatchDeleteRequest(fetchRequest: fetch)
                try mainContext.execute(request)
            }
        }

        try mainContext.save()
    } catch {
        print("error resenting the database: \(error.localizedDescription)")
    }
}

영구 상점 파일을 삭제하고 새 영구 상점 코디네이터를 설정 하시겠습니까?

fileUrlPath에서 sqlite를 삭제 한 다음 빌드하십시오.

당신이 사용하고 있다고 가정합니다 MagicalRecord 기본 영구 저장소가 있습니다.

특정 파일이 존재한다고 가정하고/또는 엔티티 이름 또는 클래스를 입력하는 것을 요구하는 모든 솔루션이 마음에 들지 않습니다. 이것은 모든 엔티티에서 모든 데이터를 삭제하는 신속한 (2)의 안전한 방법입니다. 삭제 한 후에는 신선한 스택도 재현됩니다 (실제로이 부분이 얼마나 필요한지 확실하지 않음).

모든 것을 삭제하려고하지만 작업 상점과 MOC가있는 경우 "로그 아웃"스타일 상황에 대한 Godo입니다.

extension NSManagedObject {

    class func dropAllData() {

        MagicalRecord.saveWithBlock({ context in

            for name in NSManagedObjectModel.MR_defaultManagedObjectModel().entitiesByName.keys {
                do { try self.deleteAll(name, context: context) }
                catch { print("⚠️ ✏️ Error when deleting \(name): \(error)") }
            }

            }) { done, err in
                MagicalRecord.cleanUp()
                MagicalRecord.setupCoreDataStackWithStoreNamed("myStoreName")
        }
    }

    private class func deleteAll(name: String, context ctx: NSManagedObjectContext) throws {
        let all = NSFetchRequest(entityName: name)
        all.includesPropertyValues = false

        let allObjs = try ctx.executeFetchRequest(all)
        for obj in allObjs {
            obj.MR_deleteEntityInContext(ctx)
        }

    }
}

이것을 사용하십시오

+(NSArray *)fetchDataFromEntity:(NSString *)entityName context:(NSManagedObjectContext *)context
{
    NSFetchRequest * fetchRequest =[[NSFetchRequest alloc] init];
    NSEntityDescription * CategoriesEntity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
    [fetchRequest setEntity:CategoriesEntity];

    NSError * error;
    NSInteger count = [context countForFetchRequest:fetchRequest error:&error];

    if (count && count>0) {

        NSArray * fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
        if (fetchedObjects && fetchedObjects.count>0) {

            return fetchedObjects;
        }else
            return nil;

    }
    else
        return nil;
}
+ (void)deleteObjectsOfArray:(NSMutableArray*)ary context:(NSManagedObjectContext *)context {
    for (NSManagedObject * obj in ary) {
        [context deleteObject:obj];
    }
    NSError *saveError = nil;
    [context save:&saveError];
}
+ (void)deleteEntity:(NSString *)entityName context:(NSManagedObjectContext *)context {
    NSArray *listArray = [self fetchDataFromEntity:entityName context:context];
    [self deleteObjectsOfArray:[NSMutableArray arrayWithArray:listArray] context:context];
}

나는 Grouchal의 코드를 가져 와서 속도를 높이기 위해 동시 모드와 함께 열거를 사용했습니다 (NSEnumerationConcurrent), 루프에 비해 조금 더 빨라졌습니다 (내 앱에서는 테스터 에이 기능을 추가하여 데이터를 지우고 앱을 삭제하고 설치하는 대신 테스트 케이스를 수행 할 수 있습니다).

- (void)resetObjects
{
    [self deleteAllObjectsInEntity:@"Entity1"];
    [self deleteAllObjectsInEntity:@"Entity2"];
    [self deleteAllObjectsInEntity:@"Entity3"];
    [self deleteAllObjectsInEntity:@"Entity4"];
}

-(void) deleteAllObjectsInEntity:(NSString*) entityName
{
    MainDataContext *coreDataContext = [MainDataContext sharedInstance];
    NSManagedObjectContext *currentContext = coreDataContext.managedObjectContext;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:currentContext];
    [fetchRequest setEntity:entity];

    NSError *error;
    NSArray *items = [currentContext executeFetchRequest:fetchRequest error:&error];

    [items enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSManagedObject * obj, NSUInteger idx, BOOL *stop) {
        [currentContext deleteObject:obj];
    }];


    if (![currentContext save:&error]) {
        NSLog(@"Error deleting %@ - error:%@",entityName,error);
    }
}

여기에서 모든 레코드를 삭제하기위한 내 Swift3 버전. '사용자'는 엔티티 이름입니다

@IBAction func btnDelAll_touchupinside(_ sender: Any) {

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedObjectContext = appDelegate.persistentContainer.viewContext

    let fetchReq = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
    let req = NSBatchDeleteRequest(fetchRequest: fetchReq)

    do {
        try managedObjectContext.execute(req)

    } catch {
        // Error Handling
    }   
}

iOS 10 및 Swift 3

엔티티 이름이 "사진"이라고 가정하고 Coredatastack 클래스를 생성한다고 가정합니다 ...

 func clearData() {
        do {            
            let context = CoreDataStack.sharedInstance.persistentContainer.viewContext
            let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Photo")
            do {
                let objects  = try context.fetch(fetchRequest) as? [NSManagedObject]
                _ = objects.map{$0.map{context.delete($0)}}
                CoreDataStack.sharedInstance.saveContext()
            } catch let error {
                print("ERROR DELETING : \(error)")
            }
        }
    }

다음은 Coredata를 사용하는 방법 과이 방법을 사용하는 방법에 대한 좋은 자습서입니다.https://medium.com/compileswift/parsing-json-response-and-save-in-coredata-step-pb58fc6ce16f#.1tu6kt8qb

다른 방법 (배치 삭제 요청과는 별도로 앱 요구 사항을 기준으로 사용하는 경우)은 영구 저장소를 재설정하는 것입니다. 구현은 iOS 10+ 및 Swift (Coredatamanager 클래스가 있다고 가정)에 대해 다음과 같습니다.

let persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "<Data-Model-Name>“)
    container.loadPersistentStores(completionHandler: { (storeDescription, err) in
        if let err = err {
            fatalError("loading of store failed: \(err)")
        }
    })
    return container
}()

func resetPersistentStore() {

    if let persistentStore = persistentContainer.persistentStoreCoordinator.persistentStores.last {
        let storeURL = persistentContainer.persistentStoreCoordinator.url(for: persistentStore)

        do {
            try persistentContainer.persistentStoreCoordinator.destroyPersistentStore(at: storeURL, ofType: NSSQLiteStoreType, options: nil)
        } catch {
            print("failed to destroy persistent store:", error.localizedDescription)
        }

        do {
            try persistentContainer.persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
        } catch {
            print("failed to re-add persistent store:", error.localizedDescription)
        }
    }

}

이 방법의 장점 중 하나는 특히 핵심 데이터에 수많은 엔티티에 대한 데이터 레코드가 많이있을 때 더 간단하다는 것입니다. 이 경우 배치 요청 삭제는 메모리 집약적입니다.

당신은 모두 이것을 복잡해 보이게합니다. nsmanagedObjectContext를 재설정 메소드로 보낼 수 있습니다

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top