2015-09-28 4 views
0

я есть тестовый массив со структурой объектов - группе (NSMutableArray) элементов, и я сохранить группу в YapDatabaseКак сопоставить массив в объекте YAPdatabase?

-(void)parseAndSaveJson:(id) json withCompleteBlock:(void(^)())completeBlock{ 

NSMutableArray *groupsArray = (NSMutableArray *)json; 

if (groupsArray != nil) { 

    YapDatabaseConnection *connectnion = [[DatabaseManager sharedYapDatabase] newConnection]; 

    [connectnion asyncReadWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) { 

     for (int groupIndex = 0; groupIndex < [groupsArray count]; groupIndex ++) { 

      LocalGroupsExercise *localGroup = [[LocalGroupsExercise alloc] init]; 

      localGroup.name = groupsArray[groupIndex][LOCAL_GROUPS_NAME]; 

      localGroup.tagColor = groupsArray[groupIndex][LOCAL_GROUPS_TAG_COLOR]; 

      localGroup.idGroup = [groupsArray[groupIndex][LOCAL_GROUPS_ID_GROUP] intValue]; 

      if (groupsArray[groupIndex][LOCAL_GROUPS_EXERCISES] != nil) { 

       NSMutableArray *exerciseArray = (NSMutableArray *)groupsArray[groupIndex][LOCAL_GROUPS_EXERCISES]; 

       for (int exerciseIndex = 0; exerciseIndex < [exerciseArray count]; exerciseIndex ++) { 

        LocalExercise *localExercise = [[LocalExercise alloc] init]; 

        localExercise.name = exerciseArray[exerciseIndex][EXERCISE_NAME]; 

        localExercise.exerciseId = [exerciseArray[exerciseIndex][LOCAL_EXERCISE_ID_EXERCISE] intValue]; 

        localExercise.groupId = localGroup.idGroup; 

        localExercise.type = [exerciseArray[exerciseIndex][EXERCISE_TYPE] intValue]; 

        localExercise.minWeight = [exerciseArray[exerciseIndex][EXERCISE_MIN_WEIGHT] floatValue]; 

        localExercise.maxWeight = [exerciseArray[exerciseIndex][EXERCISE_MAX_WEIGHT] floatValue]; 

        localExercise.minReps = [exerciseArray[exerciseIndex][EXERCISE_MIN_REPS] intValue]; 

        localExercise.maxReps = [exerciseArray[exerciseIndex][EXERCISE_MAX_REPS] intValue]; 

        localExercise.minTimer = [exerciseArray[exerciseIndex][EXERCISE_MIN_TIMER] intValue]; 

        localExercise.maxTimer = [exerciseArray[exerciseIndex][EXERCISE_MAX_TIMER] intValue]; 

        localExercise.timeRelax = [exerciseArray[exerciseIndex][EXERCISE_RELAX_TIME] intValue]; 

        [localGroup.exercises addObject:localExercise]; 

       } 
      } 

      [transaction setObject:localGroup forKey:[NSString stringWithFormat:@"%d", localGroup.idGroup] inCollection:LOCAL_GROUPS_CLASS_NAME]; 
     } 

     YapDatabaseConnection *connectnion = [[DatabaseManager sharedYapDatabase] newConnection]; 

     [connectnion readWithBlock:^(YapDatabaseReadTransaction *transaction) { 

      LocalGroupsExercise *group = [transaction objectForKey:@"2" inCollection:LOCAL_GROUPS_CLASS_NAME]; 

      NSLog(@"%@", group.name); 
      NSLog(@"%@", group.tagColor); 
      NSLog(@"%@", group.exercises); 

     }]; 

    } completionBlock:^{ 

     completeBlock(); 

    }]; 
} 

}

+ (YapDatabaseView *)setupDatabaseViewForShowGroupsGyms{ 

YapDatabaseViewGrouping *grouping = [YapDatabaseViewGrouping withObjectBlock:^NSString *(YapDatabaseReadTransaction *transaction, NSString *collection, NSString *key, id object) { 

    if ([object isKindOfClass:[LocalGroupsExercise class]]) { 

     LocalGroupsExercise *groupExercise = (LocalGroupsExercise *)object; 

     return [NSString stringWithFormat:@"%@", groupExercise.name]; 
    } 

    return nil; 
}]; 


YapDatabaseViewSorting *sorting = [YapDatabaseViewSorting withObjectBlock:^NSComparisonResult(YapDatabaseReadTransaction *transaction, NSString *group, NSString *collection1, NSString *key1, LocalGroupsExercise *obj1, NSString *collection2, NSString *key2, LocalGroupsExercise *obj2) { 

    return [obj1.name compare:obj2.name options:NSNumericSearch range:NSMakeRange(0, obj1.name.length)]; 
}]; 

YapDatabaseView *databaseView = [[YapDatabaseView alloc] initWithGrouping:grouping sorting:sorting versionTag:@"0"]; 

return databaseView; 

}

[[DatabaseManager sharedYapDatabase] registerExtension:self.databaseGroupView withName:LOCAL_GROUPS_CLASS_NAME]; 

[_connection beginLongLivedReadTransaction]; 


self.mappingsGroup = [[YapDatabaseViewMappings alloc] initWithGroupFilterBlock:^BOOL(NSString *group, YapDatabaseReadTransaction *transaction) { 

    return true; 

} sortBlock:^NSComparisonResult(NSString *group1, NSString *group2, YapDatabaseReadTransaction *transaction) { 

    return [group1 compare:group2]; 

} view:LOCAL_GROUPS_CLASS_NAME]; 


[_connection readWithBlock:^(YapDatabaseReadTransaction *transaction) { 
    [self.mappingsGroup updateWithTransaction:transaction]; 
}]; 

Проблема заключается в том, что группа будет NSMutabblArray, и я хочу видеть объекты в таблице массива, но [self.mappingsGroup numberOfItemsInSection: section] возвращает только один элемент в группе

ответ

1

Вам необходимо настроить YapDatabase для использования мантии. По умолчанию он будет использовать NSCoding. (Вот почему вы видите сообщение об ошибке «encodeWithCoder:», поскольку этот метод является частью NSCoding.)

Посмотрите на статью wiki YapDatabase, озаглавленную «Хранение объектов», в которой говорится о том, как она использует сериализатор/десериализации блоки: https://github.com/yaptv/YapDatabase/wiki/Storing-Objects

в основном, когда вы Alloc/инициализации экземпляра YapDatabase, вы хотите передать десериализатор блок сериализатору &, который использует Мантия для выполнения сериализации/десериализации.

Кроме того, увидеть различные инициализации методы, которые доступны для YapDatabase: https://github.com/yaptv/YapDatabase/blob/master/YapDatabase/YapDatabase.h

+0

я использую NSCoding, и никаких ошибок см, проблема в том, что группа будет NSMutabblArray, и я хочу, чтобы видеть объекты в таблице из массив –

Смежные вопросы