核心数据错误:' AnyObject'没有名为' Generator'的成员

时间:2015-01-02 08:09:39

标签: core-data swift

我无法弄清楚这里有什么问题。

代码只是将usernamepassword添加到实体“Users”,然后检索它。

代码工作正常,直到我在其中添加了for循环。我甚至尝试将AnyObject投射到NSManagedObject(据我所知,这不是必需的)

代码:

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("Rob", forKey: "username")

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


context.save(nil)

var request = NSFetchRequest(entityName: "Users")

request.returnsObjectsAsFaults = false

var results = context.executeFetchRequest(request, error: nil)

println(results)

if results?.count > 0 {

for result: AnyObject in results!{


println(result)

}

} else {

println("No results")

}

}

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


 }

错误显示在for循环的行中:for results

2 个答案:

答案 0 :(得分:1)

将您的for循环更改为此

for result: AnyObject in results! {

            if let user: AnyObject = result.valueForKey("username") {

                println(user)

            }

        }

使用valueForKey是重要的部分

答案 1 :(得分:0)

尝试以下内容。

 let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
 let managedContext = appDelegate.managedObjectContext!


 //Adding part...
 var entity = NSEntityDescription.entityForName("Users", inManagedObjectContext: managedContext)
 var user= NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
 user.setValue("Rob", forKey: "username")
 user.setValue("Pass", forKey: "password")
 var error : NSError?
 if !managedContext.save(&error) {
     println("Could not save \(error), \(error?.userInfo)")
 }

//Fetching part...
let fetchRequest : NSFetchRequest = NSFetchRequest(entityName: "Users")
 let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject]?
 if let results = fetchedResults {
     for result in results {
            //Consider that the results are array of NSManagedObject, 
            //so the value have to be unwrapped by the key. ie., result.valueForKey("username") as String
            println("\(result)")

 }

希望这有帮助。