核心数据问题Swift [英] Core data issue Swift
问题描述
您好我目前正在关注一个使用旧版本的Swift的Swift教程,我无法跟随这个,因为我相信在新版本的Swift中的语法已经改变。
Hello I am currently following a Swift tutorial which uses the old version of Swift and I am not able to follow this as I believe the syntax has changed in the newer version of 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在结果和错误是未解决的标识符'结果',这让我的印象是,这应该声明某处作为一个变量,因为它目前未解决,但我不知道如何解决这个,任何帮助非常感谢!
The error I am receiving is to do with the results on the line for result: AnyObject in results and the error is unresolved identifier 'results' which is giving me the impression that this should be declared somewhere as a variable as it is currently unresolved but I cannot figure out how to fix this, any help would be greatly appreciated, thanks!
推荐答案
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)
}
范围内的
do
块。您需要在 do
中移动数组的处理:
results
only has scope inside the do
block there. You need to move the processing of the array inside the 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
。
Also there's no need to lose information by casting as AnyObject
.
这篇关于核心数据问题Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!