ios - 添加到核心数据时如何避免重复?

标签 ios iphone core-data

我想知道如何避免添加重复数据?我想通过具有唯一行的列来做到这一点,如果该列不是唯一的,则不允许添加整行。目前我像这样添加行......

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];

最佳答案

您可以设置一个反射(reflect)您独特内容的 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
}

希望这对您有所帮助。

关于ios - 添加到核心数据时如何避免重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24334679/

相关文章:

ios - "Expected Declaration"userDefaults 中的 Swift 错误

ios - 如何在 ios 中删除 COCOS2d v3.x 中的两个 Sprite

iphone - 如何将 touchesEnded 转移到由 touchesBegan 在不同的 UIView 上添加的 UIView?

ios - 具有不同自动旋转选项的屏幕

ios - iCloud 无处不在的容器在删除应用程序时没有被清理?

ios - 通过 iCloud 仅同步我的 coreData 的 "some"

iphone - 使用 CGAffineTransform 缩放并设置 anchor

iphone - 如何在 iPhone 中查找 Scroll View 或 WebView 内容的高度

iphone - 如何根据indexPath获取单元格文本?

swift - 未捕获的异常 'NSInvalidArgumentException' ,原因 : '-[SubResultComponent setDate:]: unrecognized selector sent to instance 0x60000046b640'