在Realm迁移期间,如何进行多对一迁移?

时间:2017-04-11 19:59:11

标签: objective-c swift realm realm-migration

这就是我的意思。

我们说我们有很多数据,每个数据都有一个日期。

a: 2017/04/20
b: 2017/04/23
c: 2017/04/29
d: 2017/05/02
e: 2017/05/04

我们的目标是停止以这种方式存储数据,我们只希望每月存储汇总数据。因此,我们希望在月份04的示例中汇总数据a& b& c,并在月05汇总数据d& e。

所以最后我们只想要2个数据。

在迁移中执行此操作是否合理,或者它不是真正的地方,或者甚至可能不可能?

基本上在[migration enumerateObjects:Data.className block:^(RLMObject *oldObject, RLMObject *newObject) {我们需要进入并计算数据的月份,并保持运行总计。我们需要一些命令让域在此时不迁移特定的数据(因为我们不想在聚合完成之前)。然而,我们知道的唯一方法是当我们从c移动到d,或从04年到05年。此时,我们知道我们有运行计数/汇总数据......我猜测它&# 39;现在太晚了。

有人知道这样的事情是否可行?我猜不是,它确实没有意义......但也许有人知道它肯定不起作用或者有办法实现它。

1 个答案:

答案 0 :(得分:0)

是的,您应该可以在迁移中执行此操作。

您可以多次遍历Realm文件中的所有对象,因此 应该只是迭代所有对象,聚合每个月的值,然后迭代通过列表第二次应用新值。您还可以删除迁移块内的对象,这样您也可以确保每月只剩下一个对象:

id migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {

    // Use a dictionary to store the aggregate values.
    // Dictionary keys must be unique, so they can be used to aggregate multiple values for a month.
   NSMutableDictionary *months = [[NSMutableSet alloc] init];

   //Loop through each object to extract and aggregate the data for each month
   [migration enumerateObjects:Data.className block:^(RLMObject *oldObject, RLMObject *newObject) {

        // Extract the month value from the date in this object
        NSDate *date = newObject["date"]; // Properties can be retrieved from RLMObject via KVC
        NSInteger month = date.month.intValue; // Extract the month from that date

        // Track if this was the first entry for this specific month
        BOOL firstTime = ([months.allKeys indexOfObject:@(month)] == NSNotFound);

        // Aggregate the value of month with the value stored in the dictionary
        NSInteger aggregateValue = months[@(month)].intValue;
        aggregateValue += date; // Add the month's information to the aggregate
        months[@(month)] = @(aggregateValue);

        // If this isn't the first object, we don't need it in Realm anymore, so delete it
        if (!firstTime) {
            [migration deleteObject:newObject];
        }
    }];

    // At this point, `months` will contain our aggregate values, and the Realm database
    // only has one object per month now.

    // Loop through all the objects again so we can add in the aggregate values
    [migration enumerateObjects:Data.className block:^(RLMObject *oldObject, RLMObject *newObject) {
        NSDate *date = newObject["date"];
        NSInteger month = date.month.intValue;

        // Copy in the aggregate value
        newObject["date"] = months[@(month)];
    }];
}

话虽这么说,迁移是针对数据库的实际架构发生变化而设计的。在这种情况下,您的架构看起来没有变化,而只是您要存储的数据的粒度。

如果是这种情况,您可能更适合编写自己的辅助函数,该函数在应用程序启动时运行,检查您的数据是否已经聚合,并在检测到它时执行聚合“T

相关问题