2015-04-23 44 views
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和有沒有挑戰

enter image description here

有沒有辦法做到這一點?

這裏是在GitHub上的代碼的鏈接:lewissk/RealmTest

回答

6

領域支持的子類,但不是那種多態的,你要尋找的。在Realm中,每個對象類型都存儲在自己的表中,而不管您是否已將其作爲另一個對象的子類在代碼中聲明。這意味着目前不可能跨不同的對象類進行查詢,即使它們共享一個通用的超類。在https://github.com/realm/realm-cocoa/issues/1109處有一個跟蹤此功能請求的問題。