如何在 Swift 中的 Realm.io 中做抽象实体
Posted
技术标签:
【中文标题】如何在 Swift 中的 Realm.io 中做抽象实体【英文标题】:How to do Abstract Entities in Realm.io in Swift 【发布时间】:2015-04-23 19:48:47 【问题描述】:我正在从 CoreData 转换到 Realm.io 我做了一个小实验来看看 Realm.io 如何处理我需要有一个 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 或 A 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,并且没有任何挑战
有没有办法做到这一点?
这里是github中的代码链接:lewissk/RealmTest
【问题讨论】:
【参考方案1】:Realm 支持子类化,但不支持您正在寻找的那种多态性。在 Realm 中,每个对象类型都存储在自己的表中,无论您是否在代码中将其声明为另一个对象的子类。这意味着目前不可能跨不同的对象类进行查询,即使它们共享一个公共超类。在 https://github.com/realm/realm-cocoa/issues/1109 跟踪此功能请求时出现问题。
【讨论】:
以上是关于如何在 Swift 中的 Realm.io 中做抽象实体的主要内容,如果未能解决你的问题,请参考以下文章