Core Data - Change NSManagedObject array into array of Strings using valueForKey -OSX

1.2k views Asked by At

So iv using an NSTokenField to allow data entry, the TokenField will suggest thing when the user starts typing. I want it to suggest things that are already inside core data.

To do this i have this function being called when the cell moves to superview (This is all happening inside a custom table view cell)

var subjectInformation = [NSManagedObject]()

  let appDel = NSApplication.sharedApplication().delegate as! AppDelegate

    let context = appDel.managedObjectContext

    let fetchRequest = NSFetchRequest(entityName: "SubjectInformation")

    do {
        let results = try context.executeFetchRequest(fetchRequest)
        subjectInformation = results as! [NSManagedObject]
    } catch {

    }

this returns an array of NSManagedObjects, now i want for every object in managed object get get the valueForKey("subjectName") as insert it into a array of string so that i can return that inside this token field Function

func tokenField(tokenField: NSTokenField, completionsForSubstring substring: String, indexOfToken tokenIndex: Int, indexOfSelectedItem selectedIndex: UnsafeMutablePointer<Int>) -> [AnyObject]? {

return subjectInformation //this is where is should return an array eg; ["English","Maths","Science"]

How would i do this? Thanks :)

2

There are 2 answers

1
Scott Thompson On

Try this:

(subjectInformation as! NSArray).valueForKeyPath("@unionOfObjects.subjectName")

This should return an array of the subjectNames of all the subjectInformation items.

0
Mundi On

If you properly subclassed your NSManagedObject you can use expressive Swift style filters and maps. You would cast your results array to [SubjectInformation] and

let subjectList = subjectInformation.map { $0.subjectName }