Swift gets a specific NSManagedObject from an object (master data)

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!

+6
source share
2 answers

the valueForKey method returns an optional parameter, you can use if let , as shown below

 if let questionsArr = res.valueForKey("\(sport)") as? NSMutableArray { return questionsArr } else { return [] } 

This works in Xcode 6.3.2, but it looks like you are using an older one. If this is an update to the last.

+1
source

I'm not sure that I clearly understand what you are trying to achieve. But using the following function (using KVC), you can get a list of class properties and check if there is one that you need:

 func getPropertyList(#classToInspect: AnyObject.Type) -> [String] { var count : UInt32 = 0 let properties : UnsafeMutablePointer <objc_property_t> = class_copyPropertyList(classToInspect, &count) var propertyNames : [String] = [] let intCount = Int(count) for var i = 0; i < intCount; i++ { let property : objc_property_t = properties[i] let propertyName = NSString(UTF8String: property_getName(property))! propertyNames.append(propertyName as String) } free(properties) println(propertyNames) return propertyNames } 
+1
source

Source: https://habr.com/ru/post/988983/


All Articles