Swift 使用谓词获取核心数据
我有两个核心数据实体,一个叫做Person,另一个叫做Codes。一个人与代码有一对多的关系 我希望检索特定人员的所有代码,并具有以下功能:Swift 使用谓词获取核心数据,swift,core-data,Swift,Core Data,我有两个核心数据实体,一个叫做Person,另一个叫做Codes。一个人与代码有一对多的关系 我希望检索特定人员的所有代码,并具有以下功能: static func fetchCodes(person: Person) -> [Codes]? { let context = getContext() let fetchRequest : NSFetchRequest<Codes> = Codes.fetchRequest() let sortDesc
static func fetchCodes(person: Person) -> [Codes]? {
let context = getContext()
let fetchRequest : NSFetchRequest<Codes> = Codes.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: #keyPath(Codes.number), ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
//print("person in fetchCodes=\(person.first)")
fetchRequest.predicate = NSPredicate(format: "whosAccount == %@", person)
do {
let codes: [Codes] = try context.fetch(Codes.fetchRequest())
//print("Codes count from fetchCodes: \(codes.count)")
return codes
} catch {
return nil
}
}
static func fetchCodes(person:person)->[code]?{
let context=getContext()
let fetchRequest:NSFetchRequest=Codes.fetchRequest()
设sortDescriptor=NSSortDescriptor(键:#键路径(Codes.number),升序:true)
fetchRequest.sortDescriptors=[sortDescriptor]
//打印(“fetchCodes中的人=\(person.first)”)
fetchRequest.predicate=NSPredicate(格式:“whosAccount==%@”,person)
做{
let code:[code]=尝试上下文.fetch(code.fetchRequest())
//打印(“fetchCodes中的代码计数:\(Codes.count)”)
返回码
}抓住{
归零
}
}
我已经检查了参数
person
实际上是我想要检索代码的正确的人,但是结果返回了所有人的所有代码。我缺少什么?您不需要获取或谓词,您可以作为属性访问关系
let codes = person.codes
由于您拥有
人员
,因此不需要获取任何数据,只需从关系中获取代码
static func fetchCodes(person: Person) -> [Codes] {
return person.codes
}
您缺少的是一个输入错误:
context.fetch(code.fetchRequest())
应该是context.fetchRequest(fetchRequest)
@pbasdf:谢谢。这就是问题所在谢谢你。这是一个更简洁的解决方案。这将返回一个如下所示的集:第一个代码是:可选的((实体:code;id:0x61480dce0533d92b;数据:{code=RY6;number=1;whosAccount=“0x61480dce3c73d90b”;}))
。如何提取代码和数字元素?此外,我还需要根据number元素对集合进行排序。我认为您应该阅读,但您可以迭代集合以访问所有Codes对象。Set是无序的,但是有sorted
方法可以调用以返回排序数组。我对Xcode/swift相当陌生,并且已经阅读了Set文档,但是不知道如何过滤person返回的Set。code
如果我过滤number=1