gpt4 book ai didi

swift - 如何对数组中的每个对象执行 fetchRequest 计数?

转载 作者:行者123 更新时间:2023-11-30 13:23:57 24 4
gpt4 key购买 nike

我有 2 个实体:

出席:

import Foundation
import CoreData

extension Attendance {

@NSManaged var date: NSDate?
@NSManaged var id: NSNumber?
@NSManaged var id_consultant: String?
@NSManaged var id_store: NSNumber?
@NSManaged var name: String?
@NSManaged var status: String?

}

和产品:

import Foundation
import CoreData

extension Product {

@NSManaged var id: String?
@NSManaged var name: String?
@NSManaged var preco: String?
@NSManaged var attendance: Attendance?

}

我正在获取所有出勤,并且需要执行获取来计算出勤中有多少产品:

这是我获取考勤的方法。如何获取带有考勤 ID 的产品数量?

  func fetchAttendances() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

let managedContext = appDelegate.managedObjectContext

let fetchRequest = NSFetchRequest(entityName: "Attendance")
let attendancePredicate = NSPredicate(format: "id_store == \(Int(Helper.userDefaults().objectForKey(ConstantHelper.kIdStore)! as! NSNumber))")
fetchRequest.predicate = attendancePredicate

do {
let results = try managedContext.executeFetchRequest(fetchRequest)
myAttendances = results as! [NSManagedObject]



self.collectionAttendances.reloadData()
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}

最佳答案

假设您已设置数据模型,以便考勤和产品具有一对多关系...

Attendance <---->> Product

...您可以利用 map 语法以非常简洁的方式完成此操作:

let countArray = attendanceArray.map { ($0.id, $.products?.count ?? 0) }

这将返回一个包含 id 和产品数量的元组数组。

关于swift - 如何对数组中的每个对象执行 fetchRequest 计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37437843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com