ios - 在我的应用程序中向左/向右滑动会触发将数据保存到我的数据库的操作。然而,快速滑动会导致许多保存失败

标签 ios objective-c cocoa-touch asynchronous parse-platform

我已经实现了类似于 tinder 的滑动功能,但在保存对象时遇到了问题。

我的数据库中当前用户的行中有 2 列。一列包含一组 acceptedUsers(用户已被点赞),另一列是 rejectedUsers 列,包含一组被拒绝的用户(已被刷过的用户)。

这是我的数据库在滑动时更新的方式:

-(void)cardSwipedLeft:(UIView *)card;
{
    NSString *swipedUserId = [[[userBeingSwipedArray objectAtIndex:0] valueForKey:@"user"] valueForKey:@"objectId"];

    [currentUserImagesRow addUniqueObject:swipedUserId forKey:@"rejectedUsers"];
    [currentUserImagesRow saveInBackground];

当我在两次滑动之间留出大约 2 秒以上时,这很好用。但是,快速滑动会导致某些保存失败。

有没有更好的方法可以在不破坏应用用户体验的情况下做到这一点?

在使用 for 循环之前,我已经将多行保存到我的数据库中,这对我来说一直很有效。我认为 parse.com 能够处理保存的速度。

我在这个项目中同时使用了 swift 和 objective-c。

谢谢你的时间

最佳答案

这是一个有趣的问题。我认为要走的路是将滑动和节省更多地分离。从收集需要保存的东西开始......

@property(nonatomic, strong) NSMutableArray *toSave;
@property(nonatomic, assign) BOOL busySaving;

    // on swipe
    [self.toSave addObject: currentUserImagesRow];
    [self doSaves];

- (void)doSaves {
    // we get called because of user interaction, and we call ourselves
    // recursively when finished.  keep state so these requests don't pile up
    if (self.busySaving) return;

    if (self.toSave.count) {
        self.busySaving = YES;
        [PFObject saveAllInBackground:self.toSave block:^(BOOL succeeded, NSError *error) {
            self.busySaving = NO;
            // remove just the elements that were saved, remaining aware that
            // new ones might have arrived while the last save was happening
            NSMutableArray *removes = [@[] mutableCopy];
            for (PFObject *object in self.toSave) {
                if (!object.isDirty) [removes addObject:object];
            }
            [self.toSave removeObjectsInArray:removes];
            [self doSaves];
        }];
    }
}

现在,我们可以处理小批量,而不是处理单个保存。用户滑动会导致一次保存,并且我们会阻止其他请求,直到当前请求完成为止。在当前请求期间,随着用户继续交互,我们让更多的保存排队。我们在保存后递归调用自己,以防一条或多条记录排队。如果没有,递归调用立即结束。

编辑 - 只保存一个对象更容易,只需在最后执行相同的阻塞技巧和递归调用,但无需跟踪或保存批处理...

@property(nonatomic, assign) BOOL busySaving;

    // on swipe
    [self doSaves];

- (void)doSaves {
    if (self.busySaving) return;
    if (currentUserImagesRow.isDirty) {
        self.busySaving = YES;
        [currentUserImagesRow saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            self.busySaving = NO;
            [self doSaves];
        }];
    }
}

关于ios - 在我的应用程序中向左/向右滑动会触发将数据保存到我的数据库的操作。然而,快速滑动会导致许多保存失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28950982/

相关文章:

ios - 保留分配和初始化计数

ios - 检查设备是否禁用应用内购买

ios - 需要有关在 iOS 中请求通知权限的说明

ios - UIViewanimationWithDuration递归导致抖动

ios - AVCaptureSession如何使静音输入音频设备?

ios - 为弹出 View Controller 创建一个 NIB 文件

iphone - U_ILLEGAL_ARGUMENT_ERROR 导致我的应用程序崩溃

ios - Google map 中的折线点击

ios - 不通过 Xcode 运行时应用程序崩溃

objective-c - 在 UICollectionViewCell 中滑动 UIView 会阻止滚动能力