Objective c 核心数据获取请求中是否需要谓词?
我想在NSFetchRequest中省略谓词,以便删除实体的所有托管对象 但是,如果没有谓词(根据SQL调试器),则不会执行fetch请求。根据苹果的说法,谓词应该是可选的 我需要如何更改代码以删除谓词?有什么想法吗?谢谢大家!Objective c 核心数据获取请求中是否需要谓词?,objective-c,ios,core-data,nsmanagedobject,nsfetchrequest,Objective C,Ios,Core Data,Nsmanagedobject,Nsfetchrequest,我想在NSFetchRequest中省略谓词,以便删除实体的所有托管对象 但是,如果没有谓词(根据SQL调试器),则不会执行fetch请求。根据苹果的说法,谓词应该是可选的 我需要如何更改代码以删除谓词?有什么想法吗?谢谢大家! - (void)deleteEntity:(NSString*)entityName inContext:(NSManagedObjectContext *)context { NSFetchRequest * request= [[NSFe
- (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请求。如何确保在核心数据数据库准备就绪之前不调用我的请求?如果不需要谓词,就不分配它。删除以下行:
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"category = 'est'"];
[request setPredicate:predicate];
在核心数据数据库准备就绪之前,我发出了获取请求 为了解决这个问题,我现在将调用
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]];
}
}
会发生什么?你收到错误信息了吗?它会自动失败吗?Stephen,请求返回一个空的NSArray(count=0)。在调试器窗口中检查SQL代码时,当谓词未写入时,我看不到任何SQL命令。但是,当包含谓词时,请求可以正常运行;R.A.我已经更新了我的问题…当我删除这些行时,我的代码不起作用(如我在上面的评论中所述)。我一直这样做,并得到我的结果,在执行请求之前检查数据库中是否有表结构实体。您可以尝试:request.predicate=nil;你仍然没有任何关于它何时崩溃的调试信息吗?仅凭数组计数为0的信息很难看出有什么问题。我猜您的NSManagedObjectContext可能有问题,只需检查它是否创建正确并且没有被破坏。似乎我在数据库准备就绪之前调用了我的获取请求,我已通过NSLog语句验证了这一点。越是出错,调试就越好:-)