I have an object in my " ProjName.xcdatamodel " named "Questions". In this entity, I have 5 attributes (“hockey”, “volleyball”, “soccer”, ...), each with a transformable type. Each row (attribute) will be filled with NSMutableArray. I want to do to get the value of a specific attribute in this entity. This is my code:
func readQuestionsFromCore(sport:NSString) -> NSMutableArray { var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate) var context:NSManagedObjectContext = appDel.managedObjectContext! var request = NSFetchRequest(entityName: "Questions") request.returnsObjectsAsFaults = false var results: NSArray = context.executeFetchRequest(request, error: nil)! var qArr:NSMutableArray! if results.count > 0 { var res = results[0] as NSManagedObject qArr = res.valueForKey("\(sport)") as NSMutableArray return qArr } else { qArr = [] return qArr } }
This, of course, does not work, since I take the first index of the results from the database ( results[0] as NSManagedObject ), and thus it will fail if this element does not match the ForKey value that I am looking for.
How to get one row of results I'm looking for? That is, “football”, or at least I can somehow execute the results and compare the keys of each row of the result so that it does not crash when I try to use the wrong key? Something like this:
for (res) in results as NSManagedObject { if(res.key == "soccer") { qArr = res.valueForKey("soccer") as NSMutableArray return qArr } }
I hope I explain my explanation!
source share