How to sum the numbers(Int16) of stored core data - Swift 3

戏子无情 提交于 2020-01-23 03:32:44

问题


I have stored the letters(String), numbers(Int16) and Date(Date) in the core data. And the filter(NSPredicate) succeeded in organizing only the necessary data.

I want to get the total sum of the numbers in this core data.

  • Entity Name : Entity
  • Attribute Name : Letter(String), Value(Int16), Date(Date)

let context = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext

let entityDesc: NSEntityDescription = NSEntityDescription.entity(forEntityName: "Entity", in: context)!

let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()

request.entity = entityDesc

// Omit date NSFormatter

let dateCheck = formatter.string(from: today)

request.predicate = NSPredicate(format: "Date == %@", dateCheck)

let records = try! context.fetch(request)

I do not know what to do next. I am a beginner in development and hope someone can help.


回答1:


You have already fetch the records, so get the sum of the Value attribute this way.

try! context.fetch(request) as! [NSManagedObject]
let sum = result.reduce(0) { $0 + ($1.value(forKey: "Value") as? Int16 ?? 0) }
print(sum)


来源:https://stackoverflow.com/questions/42382971/how-to-sum-the-numbersint16-of-stored-core-data-swift-3

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