如何从coredata swift中随机选择一个元素
Posted
技术标签:
【中文标题】如何从coredata swift中随机选择一个元素【英文标题】:How to randomly choose an element from coredata swift 【发布时间】:2016-01-21 06:51:44 【问题描述】: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
中随机选择一个元素???
【问题讨论】:
【参考方案1】:斯威夫特 5
我一直在寻找这个答案,我发现你可以用 fetchOffset 得到一行,用 moc.count 得到数组计数
像这样……
func randomIconAK(_ moc: NSManagedObjectContext) -> Icon?
//
// RETURNS ONE ITEM AT RANDOM
//
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Icon")
if let fetchRequestCount = try? moc.count(for: fetchRequest)
fetchRequest.fetchOffset = Int.random(in: 0...fetchRequestCount)
fetchRequest.fetchLimit = 1
var fetchResults: [Icon]?
moc.performAndWait
fetchResults = try? fetchRequest.execute() as? [Icon]
if let wrapFetchResults = fetchResults
if wrapFetchResults.count > 0
return wrapFetchResults.first
else
return nil
else
return nil
//randomIconAK
【讨论】:
【参考方案2】:如果您尝试从数据库中的当前对象数中提取随机索引,则应使用results.count
而不是otherEntity.count
,如下所示:
@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]
【讨论】:
它不起作用。它返回一个错误,提示“无法将类型“[AnyObject]”的值分配给类型“[NSManagedObject]” 对,抱歉,结果需要是 [AnyObject] 而不是 [NSManagedObject] 类型,我已修复。 如果回答了您的问题,请接受答案。 再问一个问题。当我按下“开始”按钮时,它返回我索引超出范围。是不是因为它没有从我的核心数据中检索元素? 检查你的nameList是否为空。即使 DB 为空,randomIndex 也会为零,这是一个有效的索引,但如果 nameList 为空,那么您将超出边界异常。以上是关于如何从coredata swift中随机选择一个元素的主要内容,如果未能解决你的问题,请参考以下文章
如何从 Swift 的后台线程中从 CoreData 中获取未保存的数据?