Core Data获取请求中需要谓词?

时间:2012-04-24 09:03:11

标签: objective-c ios core-data nsmanagedobject nsfetchrequest

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

但是,如果没有谓词(根据SQL调试器),则不会执行获取请求。根据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

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

2 个答案:

答案 0 :(得分:2)

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

NSPredicate * predicate = [NSPredicate predicateWithFormat:@"category = 'est'"];
[request setPredicate:predicate];

答案 1 :(得分:0)

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

要解决此问题,我现在已将调用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]];
    }
}