你好我在Swift中遇到了核心数据的问题,这并没有显示错误,但是当我认为它应该返回时,它也不会打印任何内容#Joe;' Joe' +'传递'在控制台。有人可以帮忙吗?
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.
}
}
答案 0 :(得分:0)
您应该创建自己的coredata类(作为NSManagedObject的子类),然后从该类创建数组。
准确指定要打印的内容。在你的情况下
newUser.username
答案 1 :(得分:0)
我终于意识到我的问题是什么,我实际上并没有将实体重命名为'用户'我将其保留为'实体'所以当我做的时候
let newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject
let request = NSFetchRequest(entityName: "Users")
我应该已经用“实体”替换了两个用户,现在我已经解决了我的问题,谢谢我猜你的帮助!