I have a core-data entity with several attributes, and I want a list of all the objects in one attribute. My code looks like this:
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
let sortDesc = NSSortDescriptor(key: "username", ascending: true)
let fetchReq = NSFetchRequest(entityName: "Identities")
fetchReq.sortDescriptors = [sortDesc]
fetchReq.valueForKey("username")
let en = NSEntityDescription.entityForName("Identities", inManagedObjectContext: context)
userList = context.executeFetchRequest(fetchReq, error: nil) as [Usernames]
But this gives me an NSException-error, and I can't figure out why, or how I'm supposed to do this. I've read the NSFetchRequest class description but couldn't make much sense out of it.
Any suggestions would be appreciated.
EDIT: After a tip from Bluehound I changed my code to this:
var userList = [Model]()
@IBAction func printUsers(sender: AnyObject) {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
let sortDesc = NSSortDescriptor(key: "friendID", ascending: true)
let fetchReq = NSFetchRequest(entityName: "Identities")
fetchReq.sortDescriptors = [sortDesc]
fetchReq.propertiesToFetch = ["friendID"]
let en = NSEntityDescription.entityForName("Identities", inManagedObjectContext: context)
userList = context.executeFetchRequest(fetchReq, error: nil) as [Model]
println(userList)
}
The runtime error is gone but I still don't know if it works because I'm not sure how to convert the list to a list of strings.
As always, suggestions would be appreciated.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…