2016-09-20 273 views
0

你好,我目前正在使用一個Swift教程,它使用舊版本的Swift,我不能跟着這個,因爲我相信Swift的新版本中語法已經改變。核心數據問題Swift

class ViewController: UIViewController { 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 

    var appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 

    var context:NSManagedObjectContext = appDel.managedObjectContext 

    var newUser = NSEntityDescription.insertNewObjectForEntityForName("users", inManagedObjectContext: context) as NSManagedObject 

    newUser.setValue("Joe", forKey: "username") 

    newUser.setValue("pass", forKey: "password") 

    do { 
    try context.save() 
    } catch let error { 
     print("Couldn't save user data") 
     print(error) 
    } 

    let request = NSFetchRequest(entityName: "Users") 
     request.returnsObjectsAsFaults = false 
     // var results = context.executeFetchRequest(request) 

    do { 
     var results = 
      try context.executeFetchRequest(request) 
     results = results as! [NSManagedObject] 
    } catch let error as NSError { 
     print(error) 
    } 

    for result: AnyObject in results { 
     print(results) 
    } 
} 

我收到的錯誤是對結果的行的結果做:AnyObject的結果和錯誤是未解決的標識符「結果」,這是給我的印象中,這應該是地方宣佈爲變量,因爲它目前尚未解決,但我無法弄清楚如何解決這個問題,任何幫助將不勝感激,謝謝!

回答

1
do { 
    var results = try context.executeFetchRequest(request) 
    results = results as! [NSManagedObject] 
} catch let error as NSError { 
    print(error) 
} 

for result: AnyObject in results { 
    print(results) 
} 

results僅具有do塊有內部範圍。你需要移動陣列的處理do內:

do { 
    var results = try context.executeFetchRequest(request) 
    results = results as! [NSManagedObject] 
    for result in results { 
     print(results) 
    } 
} catch let error as NSError { 
    print(error) 
} 

也沒有必要通過鑄塑AnyObject丟失信息。

+0

(前NSFetchRequest<Users>)。啊,是的,我現在明白我要去哪裏錯了,謝謝你,但我仍然無法得到這個工作,輸出沒有顯示任何東西,當它應該顯示它從數據庫收到的值:s –

+0

啊,你的實體創建和抓取時,名稱不同 - 「用戶」和'Users'。理想情況下,這只是模型編輯器和代碼中的「用戶」。我很驚訝,不會引發異常。 – jrturton

+0

我也是,多謝隊友,奇怪...我改變了一個相應的,它似乎仍然沒有打印出來的價值:( –

0

隨着新API的反對CoreData(在雨燕3.0),你應該做的:

let request = NSFetchRequest<Users>(entityName: "Users") 
request.returnsObjectsAsFaults = false 

do { 
    var results = 
     try context.fetch(request) 
    // `results` will here be [Users] 
} catch let error as NSError { 
    print(error) 
} 

取的新的簽名是fetch<T : NSFetchRequestResult>(_ request: NSFetchRequest<T>) throws -> [T]其中T是在<HERE>提供的相同