2017-06-24 36 views
0

我正在保存一些數據 - 名稱和姓氏。但我不知道如何獲取一些數據。 這裏是我的代碼,但我不知道爲什麼它不工作 - 我不知道從核心數據獲取一些數據

class UserIN: NSManagedObject { 

    @NSManaged var name: String? 

} 

創建NSManagedObject子類

func fetching(){ 
     let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext 
     let usersFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Users") 

     do { 
      let fetchedUsers = try context.fetch(usersFetch) as! [UserIN] 
      print(fetchedUsers) 
     } catch { 
      fatalError("Failed to fetch employees: \(error)") 
     } 

    } 

請告訴我爲什麼它不不顯示提取的數據。

+0

默認的類名與實體名相同。你是否改變了課程名稱?如果是這樣,你必須在數據模型中設置它來表示實體引用這個類。 – Sweeper

+0

請顯示您如何創建(保存)數據。 – shallowThought

回答

0

類的NSManagedObject子類的實體的名稱(除非你在Interface Builder手動更改它)必須匹配

class Users: NSManagedObject { 

    @NSManaged var name: String? 

} 

不相關的問題,但在斯威夫特3使用靜態類型爲獲取請求的而不是通用的NSFetchRequestResult

func fetching(){ 
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext 
    let usersFetch = NSFetchRequest<Users>(entityName: "Users") 

    do { 
     let fetchedUsers = try context.fetch(usersFetch) 
     print(fetchedUsers) 
    } catch { 
     fatalError("Failed to fetch employees: \(error)") 
    } 

}