如何在 Swift 中实现 Realm.io 中的抽象实体

How to do Abstract Entities in Realm.io in Swift

我正在从 CoreData 转换为 Realm.io 我做了一个小实验来了解 Realm.io 如何处理我需要 class 的子 class 的情况那是一个 RLMObject。

型号

import Realm

@objc enum RecurrenceEnum : Int {
    case Daily = 1
    case Weekly = 2
    case Monthly = 3
}

class Challenge: RLMObject {
    dynamic var title = ""
}

class TotalCountChallenge: Challenge {
    dynamic var totalCountGoal: Int = 0
}

class RecurringChallenge: Challenge {
    dynamic var recurranceType: RecurrenceEnum = .Daily
    dynamic var totalCountGoal: Int = 0
}

当我保存 TotalCountChallenge 或 RecurringChallenge 时,它​​没有报告任何错误,但是当我按标题查询挑战时,我没有得到任何回复。

来自我的查询 ViewController

// Query using an NSPredicate object
let predicate = NSPredicate(format: "title BEGINSWITH %@", "Booya")
var challenges = Challenge.objectsWithPredicate(predicate)

if challenges == nil || challenges.count == 0 {
    let tcChallenge = TotalCountChallenge()
    tcChallenge.title = "Booya Total Count Challenge"
    tcChallenge.totalCountGoal = 1_000_000

    let rChallenge = RecurringChallenge()
    rChallenge.title = "Booya Recurring Challenge"
    rChallenge.recurranceType = .Weekly
    rChallenge.totalCountGoal = 2_000_000

    let realm = RLMRealm.defaultRealm()
    // You only need to do this once (per thread)

    // Add to the Realm inside a transaction
    realm.beginWriteTransaction()
    realm.addObject(tcChallenge)
    realm.addObject(rChallenge)
    realm.commitWriteTransaction()
}

challenges = Challenge.objectsWithPredicate(predicate)
if challenges != nil && challenges.count > 0 {
    for challenge in challenges {
        let c = challenge as! Challenge
        println("\(c.title)")
    }
} else {
    println("No Challenges found")
}

challenges = TotalCountChallenge.objectsWithPredicate(predicate)
if challenges != nil && challenges.count > 0 {
    for challenge in challenges {
        let c = challenge as! Challenge
        println("TotalCountChallenge: \(c.title)")
    }
} else {
    println("No Total Count Challenges found")
}

challenges = RecurringChallenge.objectsWithPredicate(predicate)
if challenges != nil && challenges.count > 0 {
    for challenge in challenges {
        let c = challenge as! Challenge
        println("RecurringChallenge \(c.title)")
    }
} else {
    println("No Recurring Challenges found")
}

输出

No Challenges found
TotalCountChallenge: Booya Total Count Challenge
RecurringChallenge Booya Recurring Challenge

当我使用 Realm 提供的浏览工具查看数据库时,我发现只有 1 个 TotalCountChallenge 和 1 个 RecurringChallenge,并且没有挑战

有办法吗?

link github 中的代码:lewissk/RealmTest

Realm 支持子类化,但不支持您正在寻找的那种多态性。在 Realm 中,每个对象类型都存储在它自己的 table 中,无论您是否在代码中将其声明为另一个对象的子类。这意味着目前无法跨不同对象 类 进行查询,即使它们共享一个公共超类。在 https://github.com/realm/realm-cocoa/issues/1109.

跟踪此功能请求时出现问题