如何让这段代码正常工作?我正在尝试将它用于核心数据中的重复
-(void)checkForDuplicates
{
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Hovedmenu"
inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"students"
ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[request setSortDescriptors:sortDescriptors];
[sortDescriptor release];
NSError *Fetcherror;
NSMutableArray *mutableFetchResults = [[managedObjectContext
executeFetchRequest:request error:&Fetcherror] mutableCopy];
if (!mutableFetchResults) {
// error handling code.
}
if ([[mutableFetchResults valueForKey:@"users"]
containsObject:name.text]) {
//notify duplicates
return;
}
else
{
//write your code to add data
}
}
答案 0 :(得分:0)
我将删除排序描述符并使用一个集来删除重复项:
NSArray *fetchResults = [managedObjectContext
executeFetchRequest:request error:&Fetcherror];
if (!fetchResults) {
// error handling code.
}
NSArray *items = [fetchResults valueForKey:@"menuPunkt"];
NSSet *distinctItems = [[NSSet alloc] initWithArray:items];
if (items.count > distinctItems.count) {
NSLog(@"Thar be dupes aboard ship lad");
}
主要问题是您不能100%明确上下文中的副本。因此,您可能希望将menuPunkt
密钥更改为其他内容。