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]
}
}
我尝试从核心数据中随机选取一个元素,并将其设置为driverSelection文本字段。在我的代码中,我将coredata =处的元素设置为otherEntity
。这使otherEntity
成为NSmanagedObject
,但由于otherEntity
是NSmanagedObject
,我不能使用.count
方法。有没有什么方法可以让我从NSmanagedObject
中随机选择一个元素???
2条答案
按热度按时间0md85ypi1#
"雨燕5"
我一直在寻找这个答案,我发现你可以用fetchOffset得到一行,用moc.count得到数组计数
像这样...
aij0ehis2#
如果您试图从DB中的当前对象数量中提取随机索引,则应使用
results.count
而不是otherEntity.count
,如下所示: