[英]Calling method of Entity Class - CoreData: Swift 2.0
我可能會以錯誤的方式進行操作,我正在嘗試調用實體子類的方法。
func addPlayer(_name: String, _team: String, _position: String, _stats: NSDictionary){
let managedContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let entity = NSEntityDescription.entityForName("Player", inManagedObjectContext: managedContext)
let player = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
player.setValue(_name, forKey: "name")
player.setValue(_position, forKey: "position")
player.setValue(_team, forKey: "teamAbbr")
player.setValue(player.calculateTradeValue() as! Player, forKey: "tradeValue")
最后一行給我一個錯誤Value of type NSManagedObject has no member calculateTradeValue
好的,我有幾個問題。 1)您在項目中使用CoreData嗎? 這就是我猜到的,由於您使用了ManagedObjectContext,我假設您在數據模型中創建了一個名為Player的實體?
2)如果您和命名約定盡可能一致,那么您和其他人將更容易閱讀代碼。 我建議命名您的“ managedContext”->“ managedObjectContext”。 它看起來似乎無關緊要,但卻是一種很好的實踐。
3)我建議在函數外聲明您的managedObjectContext; 現在,您的代碼中唯一可以訪問ManagedObjectContext中保存的內容的位置就是此函數。 如果在任何函數之外的類頂部聲明它,則可以在整個類中對其進行訪問。
4)我不確定如何告訴您如何解決實際問題,但看看如何將我的代碼組合在一起以將對象的新實例插入managedObjectContext。 在CoreData中,我有一個名為Flick的實體,其中包含諸如flickTitle,flickReleaseDate,flickDirector等屬性。
var currentFlick: Flick?
let entityDescription: NSEntityDescription! = NSEntityDescription.entityForName("Flick", inManagedObjectContext: appDelegate.managedObjectContext)
currentFlick = Flick(entity: entityDescription, insertIntoManagedObjectContext: appDelegate.managedObjectContext)
現在,您可以自由地編寫一個獲取方法,該方法將進入您的ManagedObjectContext並提取數據供您隨意使用。 我知道很多東西,但我希望至少有一部分可以幫助您到達想要的位置!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.