【问题标题】:keyPath for relationship property count关系属性计数的 keyPath
【发布时间】:2017-01-04 15:36:05
【问题描述】:

我正在尝试为获取的结果控制器创建一个 NSPredicate,控制器应该只观察具有关系的对象(它不是 nil)并且关系的计数大于 0。

我已经看到如何使用字符串作为谓词的参数来做到这一点:

[NSPredicate predicateWithFormat:@"excludedOccurrences.@count == 0"];

来自:https://stackoverflow.com/a/1195519/4096655

但我试图摆脱文字字符串,所以我想使用关键路径。

例子:

import UIKit
import CoreData

class Animal: NSManagedObject {

    @NSManaged var name: String
    @NSManaged var friends: NSSet?
}

let keyPath = #keyPath(Animal.friends.count)

导致错误: 对成员“计数”的模糊引用

【问题讨论】:

  • 不知道有没有更好的解决方案,但是NSPredicate(format: "%K.@count = 0", #keyPath(Animal.friends)) 可以。
  • @MartinR 这是一个更好的解决方案,如果属性发生变化会导致编译时错误,谢谢!

标签: swift core-data nspredicate nsfetchedresultscontroller


【解决方案1】:

#keyPath 不知道 @count 运算符。但是你可以 将它用于“Animal.friends”键路径并附加@count 在谓词格式字符串中:

NSPredicate(format: "%K.@count = 0", #keyPath(Animal.friends))

【讨论】:

    猜你喜欢
    • 2011-09-26
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多