2014-09-04 57 views
11

我該如何檢查一個屬性是否設置在覈心數據對象中?檢查是否在Core Data中設置了屬性?

我打開我的所有核心數據對象在目錄:

var formQuestions = [Questions]() 

而我的核心數據NSManagementObject是:

@NSManaged var noticeText: String 

formQuestions [indexPath.row] .noticeText

//負載:

var fetchRequest = NSFetchRequest(entityName: "Questions") 
fetchRequest.predicate = NSPredicate(format: "forms = %@", currentForm!) 
formQuestions = context.executeFetchRequest(fetchRequest, error: nil) as [Questions] 

我的屬性「noticeText」可能是空的或沒有,所以當我創建我的核心數據對象時,可能沒有設置某些值。 (該酒店坐落在覈心數據設置爲可選)

當我現在嘗試坡口,如果有一個價值,它總是給我帶來了「EXC_BAD_ACCESS ......」

if(formQuestions[indexPath.row].noticeText.isEmpty == false) 

我可以設置一個空字符串,當我創建我的核心數據對象,但這應該不是一個好的解決方案。

那麼如何檢查(optinal)而不是設定值是否存在?

在此先感謝。

+0

'@NSManaged VAR noticeText:String' - 它不是可選的 - 使它可選!要麼 ?取決於你想要什麼 – 2014-09-04 09:17:46

+1

哦,我的錯。但是我使用Editor-> CreateNSManagedSublcass來完成這個工作,而且沒有?當我使用「可選」 - 但那不是我的問題 - 我仍然不知道如何檢查屬性是否設置。 – derdida 2014-09-04 10:15:15

回答

29

更新的Xcode 7:此問題已經解決在Xcode 7測試現在2. 可選核心數據的屬性被定義爲可選屬性 在由Xcode中產生的被管理對象的子類。編輯生成的類定義不再需要 。


(前面的答案:)

在創建NSManagedObject子類時,Xcode不會對這些被標記爲在覈心數據模型檢查「可選」的屬性定義可選屬性。 這看起來像是一個bug。

作爲一種變通方法,您可以將屬性(在你的情況as String?)轉換爲 可選,然後用可選的結合

if let notice = someManagedObject.noticeText as String? { 
    println(notice) 
} else { 
    // property not set 
} 

你的情況進行測試,這將是

if let notice = formQuestions[indexPath.row].noticeText as String? { 
    println(notice) 
} else { 
    // property not set 
} 

更新:從Xcode 6.2開始,此解決方案不再有效 並因EXC_BAD_ACCESS運行時異常而崩潰 (比較e Swift: detecting an unexpected nil value in a non-optional at runtime: casting as optional fails

下面的「舊答案」解決方案仍然有效。


(舊答案:)

正如@ Daij-Djan在評論已經指出,你必須定義一個 可選的核心數據屬性財產可選隱含展開可選

@NSManaged var noticeText: String? // optional 
@NSManaged var noticeText: String! // implicitly unwrapped optional 

不幸的是,Xcode中沒有定義可選屬性心病當創建 NSManagedObject子類時,這意味着如果在模型更改後再次創建子類,則必須重新應用更改 。

此外,這似乎仍然沒有記錄,但這兩個變種在我的測試案例中工作。

您可以== nil測試屬性:

if formQuestions[indexPath.row].noticeText == nil { 
    // property not set 
} 

或使用可選的分配:

if let notice = formQuestions[indexPath.row].noticeText { 
    println(notice) 
} else { 
    // property not set 
} 
+0

字符串和字符串有什麼區別!在這種情況下?爲什麼有必要隱式地解開它?爲什麼不把它留作字符串? – cfischer 2014-10-05 11:24:33

+1

@cfisher:一個字符串不能爲零。 - 但我會建議在Apple提交錯誤報告。 Xcode應該爲可選屬性生成正確的代碼。 – 2014-10-05 11:31:19

+0

如果downvoter可以請留下解釋評論?如果有任何問題,我會非常感興趣,並在必要時修復答案。 – 2014-11-24 13:56:52

5

您的應用程序崩潰,因爲您嘗試訪問not optional variable。這是不允許的。要解決你的問題只是添加在NSManagedObject子類?來取得的財產可選:

@objc class MyModel: NSManagedObject { 
    @NSManaged var noticeText: String? // <-- add ? here 
} 

再進行試驗,你可以像這樣的屬性:

if let aNoticeText = formQuestions[indexPath.row].noticeText? { 
    // do something with noticeText 
} 
相關問題