1

ResearchKit 有ORKOrderedTask一个类可以向其中添加指令、调查、活动等步骤。通过类映射,我确定来自服务器的给定响应属于哪一步。我的映射如下

let classMapping = [
"ORKInstructionStep": ORKInstructionStep.self,
"ORKQuestionStep": ORKQuestionStep.self,
"ORKFormStep": ORKFormStep.self,
"ORKFormItem": ORKFormItem.self
]

如果我向ORKOrderedTask. 从服务器存储数据的问题步骤结构如下

struct QuestionGroup {
let identifier, title, text : String
let answerFormat: ORKAnswerFormat
init(identifier: String, title: String, text: String, answerFormat: ORKAnswerFormat) {
    self.identifier   = identifier
    self.title = title
    self.text  = text
    self.answerFormat = ORKAnswerFormat()
}
}

我将日期从服务器存储到问题组结构中,如下所示

LIbraryAPI.sharedInstance.questionList.append(QuestionGroup(identifier: row["objectId"]!.string!, 
title: row["title"]!.string!, text: row["text"]!.string!, answerFormat: ORKBooleanAnswerFormat()))

在上面的代码中,answerFormat目前是硬编码的,但可以是以下枚举中的任何答案格式

enum AnswerFormat: Int {
case ORKScaleAnswerFormat = 0,
ORKContinuousScaleAnswerFormat,
ORKValuePickerAnswerFormat,
ORKImageChoiceAnswerFormat,
ORKTextChoiceAnswerFormat,
`ORKBooleanAnswerFormat`,
ORKNumericAnswerFormat,
ORKTimeOfDayAnswerFormat,
ORKDateAnswerFormat,
ORKTextAnswerFormat,
ORKTimeIntervalAnswerFormat
   }

对于每种答案格式,都会有不同的参数要传递。以下是我将问题步骤添加到ORKOrderedTask的最终代码。

  if let questionStep  = classMapping["ORKQuestionStep"] as? ORKQuestionStep {
    let tempStep = questionStep.dynamicType
    let group = LIbraryAPI.sharedInstance.questionList
    for eachGroup in group {
        let finalQuestionStep = tempStep(identifier: eachGroup.identifier, title: eachGroup.title, answer: eachGroup.answerFormat)
        steps += [finalQuestionStep]
    }
}

所以我的问题是服务器为每个问题传递给我不同类型的答案格式。如何动态创建AnswerFormat枚举下的每种答案格式的实例?因为ORKBooleanAnswerFormat没有任何参数,另一方面ORKTextChoiceAnswerFormat可以有一个字符串数组作为参数,并且日期答案格式必须提供最大和最小日期等等。

那么我如何管理所有这些并将其归入一个类或函数以使其可用于所有答案格式类?

4

0 回答 0