Search code examples
iosarrayscore-dataswift2nsmanagedobject

How to randomly choose an element from coredata swift


import UIKit
import CoreData

class Period1Controller: UIViewController, UITextFieldDelegate {


@IBOutlet weak var enterName: UITextField!
@IBOutlet weak var presentName: UITextView!
@IBOutlet weak var independceStatue: UITextField!
@IBOutlet weak var driverSelection: UITextField!


var entitys = [NSManagedObject]()
var nameList : [String] = []
var period1 = ""
var period1NameList = ""

override func viewDidLoad() {
    super.viewDidLoad()

}


func setValues() {
    nameList = [enterName.text!]
}

//this button is for saving the element into the core data
@IBAction func setName(sender: UIButton) {
    setValues()
    for item in nameList{
        period1 += (item + "  ")
        period1NameList += item
    }
    let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
    let entity = NSEntityDescription.entityForName("Entity", inManagedObjectContext: context)
    let otherEntity = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: context)
    otherEntity.setValue(period1NameList, forKey: "period1Core")
    do {
        try context.save()
        print("Item Saved")
    } catch {
        print("Saved Failed")
    }
    presentName.text = period1
    enterName.text = ""
}

// this button is for taking out element from core data and randomly pick a value from the element I took out from core data
@IBAction func start(sender: UIButton) {
    setValues()
    let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
    let request = NSFetchRequest(entityName: "Entity")
    do {
        let results = try context.executeFetchRequest(request)
        entitys = results as! [NSManagedObject]
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }
    let otherEntity = entitys.last
    let randomIndex = Int(arc4random_uniform(UInt32(otherEntity.count)))
    driverSelection.text! = nameList[randomIndex]

}

}

What I am trying to do is to randomly pick an element from my core data and set it equal to the driverSelection textfield. In my code I set the element at my coredata = to otherEntity. This made otherEntity a NSmanagedObject, but since the otherEntity is an NSmanagedObject, I am not able to use .count method. Is there a way that can make me able to randomly selected a element from NSmanagedObject???


Solution

  • If you are trying to pull a random index out of the current number of objects in the DB than you should use results.count not otherEntity.count like so:

        @IBAction func start(sender: UIButton) {
            setValues()
            let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
            let request = NSFetchRequest(entityName: "Entity")
            var results = [AnyObject]()
    
            do {
                results = try context.executeFetchRequest(request)
    
            } catch let error as NSError {
                print("Could not fetch \(error), \(error.userInfo)")
            }
            let randomIndex = Int(arc4random_uniform(UInt32(results.count)))
            driverSelection.text! = nameList[randomIndex]
    
        }