Realm Swift中的一对多关系怎么样?

时间:2017-03-28 08:00:07

标签: ios swift3 realm

我是Realm SWift的新手。我希望在Swift3.0中实现一对多的关系

我有文件夹列表,每个文件夹可能包含子文件夹列表。所以我创建了两个像下面这样的relam文件。

文件夹领域类

 class FolderRealm: Object {

    dynamic var folderName : String?
    dynamic var createdDate : Date?
    let subFolders = List<SubFolderRealm>()
 }

SubFolder Realm Class

 class SubFolderRealm: Object {

   dynamic var subFolderName : String?
   dynamic var createdDate : Date? 

 }

对于添加文件夹,我使用了以下代码行

let folder : FolderRealm  = FolderRealm()
folder.folderName = searchBarObj.text!
folder.createdDate = Date()
 try! realm.write {
   realm.add(folder)
 }

我有疑问,如何将子文件夹数据添加到文件夹和子文件夹领域?

2 个答案:

答案 0 :(得分:9)

首先,考虑只使用一个Folder类型,而不是两个,当所有数据相同时,没有点具有Subfolder对象。

class Folder : Object {
    dynamic var folderName:String = ""
    dynamic var createdDate:Date = Date()
}

其次,对于您的情况,您可能需要使用LinkingObjects

class Folder : Object {
    dynamic var folderName:String = ""
    dynamic var createdDate:Date = Date()
    dynamic var parentFolder:Folder? = nil

    let subfolders = LinkingObjects(fromType: Folder.self, property: "parentFolder")
}

你要创建这样的对象:

let parentFolder = Folder()
let subfolder1 = Folder()
let subfolder2 = Folder()

parentFolder.folderName = "whatever"

subfolder1.parentFolder = parentFolder
subfolder2.parentFolder = parentFolder

let realm = try! Realm()
try! realm.write { realm.add([parentFolder, subfolder1, subfolder2])}

答案 1 :(得分:1)

try! realm.write { realm.add(folder) }

之前尝试此操作
let folder : FolderRealm  = FolderRealm()
folder.folderName = searchBarObj.text!
folder.createdDate = Date()

let subFolder1: SubFolderRealm = SubFolderRealm()
subFolder1.subFolderName = "any string"
subFolder1.createdDate = Date()

let subFolder2: SubFolderRealm = SubFolderRealm()
subFolder2.subFolderName = "any string"
subFolder2.createdDate = Date()

folder.subFolders = [subFolder1, subFolder2]

try! realm.write {
    realm.add(folder)
}