您好,我在Swift中的核心数据有问题,当我认为它应该在控制台中返回“Joe”+“pass”时,这不会显示错误,也不会打印任何内容。有人能帮忙吗?

import UIKit
import CoreData

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

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

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

最佳答案

您应该创建自己的coredata类(作为NSManagedObject的子类),然后从该类中创建数组。
准确指定要打印的内容。对你来说
新用户.username

07-26 08:02