2016-09-28 192 views
0

所以我一直在學習和使用CoreData,我一直非常沮喪的下列問題。當我啓動我的應用程序時,我想取我的CoreData作爲我創建的自定義NSManagedObject子類。但強迫下來的鑄造從不起作用。我遵循Apple指南。Swift 3核心數據強制向下轉換到NSManagedObject子類

我的數據如下。下面是自定義NSManagedObject子類:

import UIKit 
import CoreData 
@objc(StudentUniversityData) 

class UniversityData: NSManagedObject { 
    @NSManaged var universityName:String 
    @NSManaged var chineseName:String 
    @NSManaged var bottomReadingPercentile:NSNumber 
    @NSManaged var bottomMathPercentile:NSNumber 
    @NSManaged var topReadingPercentile:NSNumber 
    @NSManaged var topMathPercentile:NSNumber 
} 

下面是我創建的代碼:

override func viewWillAppear(_ animated: Bool) { 
    super.viewWillAppear(animated) 

    let appDelegate = UIApplication.shared.delegate as! AppDelegate 
    let managedContext = appDelegate.managedObjectContext 
    let studentUniversityFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "StudentUniversityData") 
    studentUniversityFetchRequest.returnsObjectsAsFaults = false  
    do { 
     let studentUniversityResults = try managedContext.fetch(studentUniversityFetchRequest) 
     savedUniversities = studentUniversityResults as! [UniversityData] // the problem is HERE; this part never works 
    } catch let error as NSError { 
     print ("Could not fetch \(error), \(error.userInfo)") 
    } 
} 

Here is one picture of my CoreData entity.

Here is another picture of my CoreData entity

無論我嘗試做的savedUniversities財產永遠是零。

此外,我讀到有多個目標會搞砸代碼。所以我確保我所有的類只有一個目標(我拿出測試和UItests目標成員)。仍然不起作用。

對不起,如果這不是很清楚,因爲我很累,並已在這個問題上工作了幾個小時(沒有任何進展)。我讀過關於堆棧溢出的許多問題,如:

Unable to find specific subclass of NSManagedObject

CoreData: warning: Unable to load class named

Core Data: Could not cast value of type 'MyType_MyType_2' to MyType

但我還是堅持。

+0

你確定你的「saveContext()」?即您確定要保存數據嗎?你不能獲取不存在的數據:) –

+0

它存在。當我做「po studentUniversityResults」時,我得到了「×10元素 -0:(實體:StudentUniversityData; id:0xd000000000040002 ;數據:{ bottomMathPercentile = 500; bottomReadingPercentile = 500; 中國人名= 「\ U5927 \ U5b66 \ U4e8c」; topMathPercentile = 750; topReadingPercentile = 750; universityName = 「ASDF大學」; })」 – Hadoren

+0

這些細節不加起來。由於您使用'as!',向下轉換應該成功或導致崩潰;除非你是低調的東西,否則你不會得到零結果。如果你使用'as?',那麼零將是有意義的,但不能用'as!'。 –

回答

0

因此,我在半天后解決了我的問題。

我所做的是將我的Core Data實體重命名爲「UniversityData」。這使得它與NSManagedObject子類「UniversityData」匹配。

所有名稱匹配後都有效。

似乎很多核心數據僅適用於名稱與完全匹配與您的子類中的所有內容。

相關問題