首页 文章

集成Realm时出错

提问于
浏览
1

我正在尝试将Realm集成到我的iOS应用程序中,因此数据可以持久化 .

现在我收到这个错误:

由于未捕获的异常'RLMException'而终止应用程序,原因:'属性'部分'被声明为'NSArray',它不是受支持的RLMObject属性类型 . 所有属性必须是基元,NSString,NSDate,NSData,NSNumber,RLMArray,RLMLinkingObjects或RLMObject的子类 . 有关详细信息,请参阅https://realm.io/docs/objc/latest/api/Classes/RLMObject.html . 第一次抛出调用堆栈:...

谁能告诉我我做错了什么?

持有 sections 的对象类 .

class Workout: Object {
  dynamic var image: String = ""
  dynamic var name: String = ""
  dynamic var type: String = ""

  dynamic var sections:[String] = []

  var dayOne = List<Exercise>()
  var dayTwo = List<Exercise>()
  var dayThree = List<Exercise>()
  var dayFour = List<Exercise>()
  var dayFive = List<Exercise>()

  func addExerciseToSection(sectionName: String, exerciseName: Exercise) {
      if sectionName == "Day 1" {
        dayOne.append(exerciseName)
      } else if sectionName == "Day 2" {
        dayTwo.append(exerciseName)
      } else if sectionName == "Day 3" {
        dayThree.append(exerciseName)
      } else if sectionName == "Day 4" {
        dayFour.append(exerciseName)
      } else if sectionName == "Day 5" {
        dayFive.append(exerciseName)
      }
  }

  func getWorkoutInSection(workout: Workout, section: Int) -> List<Exercise>? {
      if section == 0 {
        return workout.dayOne
      } else if section == 1 {
        return workout.dayTwo
      } else if section == 2 {
        return workout.dayThree
      } else if section == 3 {
        return workout.dayFour
      } else if section == 4 {
        return workout.dayFive
      }
      return nil
  }
}

3 回答

  • 4

    下面的错误只是告诉您不能将某些类型分配给Realm Objects ,并指定您可以使用的类型:

    所有属性必须是基元,NSString,NSDate,NSData,NSNumber,RLMArray,RLMLinkingObjects或RLMObject的子类 .

    替换此行:

    dynamic var sections:[String] = []
    

    可以解决你的错误 . 虽然,问题在于您构建数据的方式 . 看看Sectioned tableView example . 可以在加载视图时动态创建表视图部分,无需将其保存到领域对象 .

    如果您确实要保存 section ,可以考虑使用另一个领域对象来执行此操作,例如:

    class Sections: Object{
        dynamic var section: String = "" 
    }
    
  • 0

    如果您不想保留sections属性,则需要忽略它

    override static func ignoredProperties() -> [String] {
        return ["sections"]
      }
    
  • 0

    它清楚地说你的属性 dynamic var sections:[String] = [] 是数组并且它不受支持,你可以尝试使用 var sections = List<StringObject>() 其中StringObject是Realm类包含你的字符串

相关问题