fetch core data string and place in a label (Swift4)

为君一笑 提交于 2019-11-29 18:12:05

Loop over the result from the fetch and append to a string that is then used as value for the label, this goes inside the do{...} where you do the fetch today. Note that I am only using one fetch request here.

itemsName = try context.fetch(fetchRequest)
var mergedScore: String = ""
var mergedAlba: String = ""
for item in itemsName {
    if let score = item.value(forKey: "score") as? String {
         mergedScore.append(score)
         mergedScore.append(" ") //separator
    }
    if let alba = item.value(forKey: "alba") as? String {
         mergedScore.append(alba)
         mergedScore.append(" ") //separator
    }
}
j1.text = mergedScore
j2.text = mergedAlba

Try this one it's Working for me Swift 4 I think You need to store the value as int which are used as sortDescriptor.

func FetchManagedObjectFromDatabaseForStoreData(Entity :NSEntityDescription) -> 
[NSManagedObject]
{
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>()

    // Add Sort Descriptor
    let sortDescriptor = NSSortDescriptor(key: "order", ascending: true)
    let sortDescriptor1 = NSSortDescriptor(key: "is_favourite", ascending: false)

    fetchRequest.sortDescriptors = [sortDescriptor,sortDescriptor1]

    // Create Entity Description
    fetchRequest.entity = Entity

    let result : [NSManagedObject] = []

    // Execute Fetch Request
    do{
        let result = try appDelegate.managedObjectContext.fetch(fetchRequest) as! [NSManagedObject]

    if  result.count > 0
    {
        return result

    }
    else
    {
        // return result

    }
}
catch{
    let fetchError = error as NSError
    print(fetchError)
}

return result
}

For Fetch Data

// Create Entity Description
let entityDescription = NSEntityDescription.entity(forEntityName: "Your Entity Name Here", in: appDel.managedObjectContext)

let DataObject = FetchManagedObjectFromDatabaseForStoreData(Entity: entityDescription!)

//Convert  Array of NSManagedObject into array of [String:AnyObject]     
for item in DataObject{

    let keys = Array(item.entity.attributesByName.keys)

    // Here is your result
    print((item.dictionaryWithValues(forKeys: keys) as NSDictionary).value(forKey: "id") as Any) // And so On Whatewer you Fetch

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!