3
我從CoreData轉換爲Realm.io我做了一個小實驗,看看Realm.io如何處理需要具有RLMObject類的子類的情況。如何在Realm.io中實現抽象實體
型號
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
當我看使用瀏覽工具的領域我看到提供的數據庫,世界上只有1個TotalCountChallenge和1 RecurringChallenge和有沒有挑戰
有沒有辦法做到這一點?
這裏是在GitHub上的代碼的鏈接:lewissk/RealmTest