我想弄清楚如何避免添加重复数据?我想通过使列具有唯一行来实现,如果列不唯一,则禁止添加整行。目前我添加像这样的行......
if([userProfileId isEqualToString: myId]) {
User *users = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext: _managedObjectContext];
int i = 0;
for(i = 0; i < responseCount; i++) {
[users setUserId:userIds[i]];
[users setName:names[i]];
[users setDateRetrieved:[NSDate date]];
}
//TODO HAVE TO AVOID DUPLICATE FROM BEING SAVED IN DB
NSError *error = nil;
if(![_managedObjectContext save:&error]) {
//handle error if it does not save
}
[self getDbData];
答案 0 :(得分:1)
您可以设置反映您的独特内容的NSPredicate并运行快速查询以查看该内容是否已存在:
将结果类型设置为NSManagedObjectIDResultType以加快速度:
fetchRequest.resultType = NSManagedObjectIDResultType;
然后得到计数:
NSUInteger count = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error];
然后检查:
if (count > 0){
// The unique content already exists - do nothing
}
if (count == 0){
// Save the unique content
}
希望这有帮助。