2

我想在 NSFetchRequest 中省略谓词,以便删除实体的所有托管对象。

但是,当没有谓词时(根据 SQL 调试器),不会执行 fetch 请求。根据 Apple 的说法,谓词应该是可选的。

我需要如何更改代码以删除谓词?有任何想法吗?谢谢!

- (void)deleteEntity:(NSString*)entityName inContext:(NSManagedObjectContext *)context
    {  
        NSFetchRequest * request= [[NSFetchRequest alloc] init];
        [request setEntity:[NSEntityDescription entityForName:@"TableStructure" inManagedObjectContext:context]];
        //[entities setIncludesPropertyValues:NO]; //only fetch the managedObjectID
        NSPredicate * predicate = [NSPredicate predicateWithFormat:@"category = 'est'"];
        [request setPredicate:predicate];

    NSError *error = nil;
    NSArray *entitiesArray = [context executeFetchRequest:request error:&error];

    if (error) {
        NSLog(@"%@: Error fetching context: %@", [self class], [error localizedDescription]);
        NSLog(@"entitiesArray: %@",entitiesArray);
        return;
    }

    for(NSManagedObject *entity in entitiesArray) {
        [context deleteObject:entity];
    }

    NSError *saveError = nil;
    [context save:&saveError];
}

更新 2

似乎我在数据库准备好之前调用了我的 fetch 请求。如何确保在核心数据数据库准备好之前不调用我的请求?

4

2 回答 2

2

如果您不想要它,您根本不分配谓词。删除以下行:

NSPredicate * predicate = [NSPredicate predicateWithFormat:@"category = 'est'"];
[request setPredicate:predicate];
于 2012-04-24T09:49:46.007 回答
0

我在 Core Data 数据库准备好之前发出了我的 fetch 请求。

为了解决这个问题,我现在添加了ImportFormulasInRequest对 UIDocument openWithCompletion 处理程序的调用,它封装了我的核心数据数据库:

- (void)useDocument
{
    if (![[NSFileManager defaultManager] fileExistsAtPath:[self.myDatabase.fileURL path]]) {
        // does not exist on disk, so create it
        [self.myDatabase saveToURL:self.myDatabase.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
            [self setupFetchedResultsController];
        }];
    } else if (self.myDatabase.documentState == UIDocumentStateClosed) {
        // exists on disk, but we need to open it
        [self.myDatabase openWithCompletionHandler:^(BOOL success) {
            [self setupFetchedResultsController];
            [self ImportFormulasInContext:[self.myDatabase managedObjectContext]];
        }];
    } else if (self.myDatabase.documentState == UIDocumentStateNormal) {
        // already open and ready to use
        [self setupFetchedResultsController];
        [self ImportFormulasInContext:[self.myDatabase managedObjectContext]];
    }
}
于 2012-04-24T11:21:26.280 回答