2016-06-21 42 views
0

概述連接我的NSManagedObject子與我ViewController.swift

這可能是一個非常愚蠢的/簡單的問題,但它似乎是扔我通過一個循環。根據我在StackOverflow上的研究員的建議,我爲實體「UsedInfo」創建了一個NSManagedObject子類。我的最終目標是使用此子類將用戶信息發送給CoreData,並稍後檢索它。

問題

的問題是,我無法弄清楚如何使用我的新文件,「UsedInfo + CoreDataProperties.swift」,用我的「ViewController.swift」的文件,這就是我的TextField是連接的。在下面你會找到相關的代碼。

代碼ViewController.swift(SaveButton)

@IBAction func saveButton(sender: AnyObject) { 
    let appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate) 
    let context:NSManagedObjectContext = appDel.managedObjectContext 
    let managedContext:NSManagedObjectContext = appDel.managedObjectContext 
    let entity1 = NSEntityDescription.insertNewObjectForEntityForName("UsedInfo", inManagedObjectContext:context) as NSManagedObject 

    let one = pickerTextField.text 
    let two = modelName.text 
    let three = serialNo.text 
    let four = YOM.text 
    let five = engineHours.text 
    let six = locationOfMachine.text 

    entity1.setValue(one, forKey: "product") 
    entity1.setValue(two, forKey:"modelName") 
    entity1.setValue(three, forKey:"serialNo") 
    entity1.setValue(four, forKey:"yom") 
    entity1.setValue(five, forKey:"engineHours") 
    entity1.setValue(six, forKey:"location") 
    print(entity1.valueForKey("product")) 
    print(entity1.valueForKey("modelName")) 
    print(entity1.valueForKey("serialNo")) 
    print(entity1.valueForKey("yom")) 
    print(entity1.valueForKey("engineHours")) 


    do { 
     try context.save() 
    } 
    catch { 
     print("error") 
    } 


} 

代碼 「UsedInfo + CoreDataProperties.swift」

import Foundation 
import CoreData 

extension UsedInfo { 

@NSManaged var engineHours: String? 
@NSManaged var location: String? 
@NSManaged var modelName: String? 
@NSManaged var product: String? 
@NSManaged var serialNo: String? 
@NSManaged var yom: String? 

} 

代碼 「UsedInfo.swift」

import Foundation 
import CoreData 
class UsedInfo: NSManagedObject { 

    //Insert code here to add functionality to your managed object subclass 

} 

我先謝謝你們。我很抱歉我完全禁錮。

回答

1

由於您創建了NSManagedObject的子類,因此可以使用該子類而不用任何特殊步驟來「連接」它。它已準備就緒,它可以執行任何由NSManagedObject定義的任何內容以及任何添加到新子類中的內容。

核心數據你會通過改變創建一個新的實例是這樣的

let entity1 = NSEntityDescription.insertNewObjectForEntityForName("UsedInfo", inManagedObjectContext:context) as NSManagedObject as! UsedInfo 

insertNewObjectForEntityForName(_:inManagedObjectContext:)呼叫將創建UsedInfo實例的代碼開始,但你需要的as! UsedInfo添加到明確這就是你所得到的。使用as!可能很危險,但這裏並不是一個壞主意,因爲如果這種downcast失敗了,您想立即知道,以便您可以修復您的託管對象模型。

之後,entity1是您的新UsedInfo類的一個實例。您可以在下面的代碼中使用在UsedInfo上聲明的屬性。例如,

entity1.product = one 
+0

這正是我一直在尋找的!謝謝,湯姆。我知道我的問題似乎很愚蠢,我只是不習慣iOS開發。 – gavsta707