RhysD
RhysD

Reputation: 1647

Getting specific attributes from coredata swift

I have a request for an entity in core data:

override func viewWillAppear(animated: Bool) {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext

    let fetchRequest = NSFetchRequest(entityName: "Constants")

    do {
        let results = try managedContext.executeFetchRequest(fetchRequest)
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }
}

Within the entity Constants there are 4 attributes: moneyPerSecondSave,moneySave,tapMultiplierSaveandtapValueSave. My question is, is there a way that after I have got the results can I make four variables which each hold each of the values of the attributes.

I have already tried using valueForKey:

moneyConstants.money = results.valueForKey("moneySave")

However when I try this it pulls up an error: `Value of type '[AnyObject]' has no member 'valueForKey'. Any help would be appreciated.

Upvotes: 2

Views: 3419

Answers (2)

Tuslareb
Tuslareb

Reputation: 1200

'results' is an array which holds 'Any' type. You can cast it to an array with the type you expect and get the rest of the data like this:

     if let constants = results as? [Constants] {
            let moneyPerSecond = constants[0].moneyPerSecondSave
            print("moneyPerSecond: \(moneyPerSecond)")
        }

You can also use valueForKey of course, like this:

        if let match = results[0] as? Constants {
            let money = match.value(forKey: "moneySave") as! Float
            print("money: \(money)")
        }

Upvotes: 2

ystack
ystack

Reputation: 1805

You can use propertiesToFetch & resultType attribute of NSFetchRequest to retrieve only specific property values of Constants. You can take inspiration from https://stackoverflow.com/a/6267875/3339346

Upvotes: 0

Related Questions