创建域列表的语法

时间:2015-10-23 19:11:36

标签: ios database list swift2 realm

我正在使用Realm数据库(RealmSwift),我想将列表值添加到我的数据库中。我的第一个数据库是学生数据库:

import Foundation
import RealmSwift

class Student: Object {

dynamic var identifier = ""
dynamic var name = ""
dynamic var university = ""
let subjects = List<Subjects>()  
override static func primaryKey() -> String? {
   return "identifier"
    }

  }

我的科目数据库很简单:

import Foundation
import RealmSwift

class Subjects: Object {

dynamic var identifier = ""
dynamic var name = "" 

override static func primaryKey() -> String? {
   return "identifier"
    }

  }

现在,我不确定在创建包含列表值的变量时使用的正确语法。

  try! realm.write() {
let myStudent = realm.create(Student.self, value: ["identifier" : "1",    "name" : "James", "university" : "Stanford", "subjects" : "Engineering",  "Mathematics", "Physics"] ) 

realm.add(myStudent)

我怎样才能在列表中为每个主题添加标识符?

2 个答案:

答案 0 :(得分:1)

我认为您需要首先使用一个dict创建Student,然后逐个创建Subject作为具有单独词典的Realm对象,然后将它们添加到父Student在这里:

let realm = try! Realm()

try! realm.write() {

  let studentDict = [
    "identifier" : "2",
    "name" : "James",
    "university" : "Stanford",
  ]


  let subjects = [
    [
      "name":"Misdirection",
      "identifier":"MS102"
    ],
    [
      "name":"Knitting",
      "identifier":"DDA201"
    ],
    [
      "name":"Levitation",
      "identifier":"HOP101",
    ]
  ]

  let myStudent = realm.create(Student.self,value:studentDict)


  for dict in subjects {
    let subj = realm.create(Subject.self,value:dict)
    myStudent.subjects.append(subj)
  }


  print("my student is \(myStudent)")

}

我的输出是:

my student is Student {
    identifier = 2;
    name = James;
    university = Stanford;
    subjects = RLMArray <0x7fd4d9d883a0> (
        [0] Subject {
            identifier = MS102;
            name = Misdirection;
        },
        [1] Subject {
            identifier = DDA201;
            name = Knitting;
        },
        [2] Subject {
            identifier = HOP101;
            name = Levitation;
        }
    );
}

请注意,如果运行两次此代码将失败,因为Realm不允许您插入具有相同Students值的两个identifier

答案 1 :(得分:0)

你需要使用一个数组,就像这样:

let myStudent = realm.create(Student.self, value: ["identifier" : "1",    "name" : "James", "university" : "Stanford", "subjects" : ["Engineering",  "Mathematics", "Physics"] ] )