Master data error: "AnyObject" does not have a member named "Generator"

I cannot figure out what is wrong here.

The code simply adds username

and password

to the essence of the "Users", and then remove it.

The code worked fine until I added a for loop to it. I even tried casting AnyObject

before NSManagedObject

(which is not required as far as I know)

Code:

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.
}


 }

      

The error is shown in the line of the for loop: for results

+3


source to share


2 answers


Change the for loop to

for result: AnyObject in results! {

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

                println(user)

            }

        }

      



Using valueForKey is the important part

+1


source


Try something like below.

 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)")

 }

      



Hope it helps.

0


source







All Articles