【问题标题】:Binary operator cannot be applied to NSpredicate and int二元运算符不能应用于 NSpredicate 和 int
【发布时间】:2017-03-05 05:47:11
【问题描述】:

我有一个EventDec 实体,它具有eventStatus 属性,我只想显示该属性的结果。这是我的代码

 let fetchRequestDec = NSFetchRequest<NSFetchRequestResult>(entityName: "EventDec")
    fetchRequestDec.predicate = NSPredicate(format:"eventStatus = %i")
    let result = fetchRequestDec.predicate
 if (result == 1)
    {
      print("Status = 1")
    }
    else 
    {
      print("Status = 2")
    }

因此,当我收到此错误时,我正在过滤错误。我该如何解决这个问题?

二元运算符 '==' 不能应用于 NSpredicate 和 int

【问题讨论】:

  • 不是过滤,而是结果 == 1 行。 result 是一个 NSPredicate,1 是一个 int,因此不能使用二元运算符 '=='。
  • 好的,那你怎么解决这个问题
  • 要么为 result 赋值一个 int 值(让 result = 4 或其他),要么将它与另一个 NSPredicate 进行比较(如果 result == NSPredicate(format:"eventStatus = 6"))。如果没有关于这个 sn-p 应该做什么的更多信息,我无法确切地告诉你该怎么做。你到底在检查什么?
  • eventStatus 包含值 1 和 2。所以我喜欢显示 eventStatus 内部的内容,以便我可以相应地显示消息
  • 好的。我会在一分钟内给你一个答案。我想确认我的子字符串知识是最新的。

标签: swift xcode core-data nsfetchrequest


【解决方案1】:

你为什么要使用谓词?您的问题似乎想要返回 EventDec 对象并打印 eventStatus 属性。您需要执行提取。获取结果数组。提取你想要的。无需过滤。

let fetchRequest: NSFetchRequest<EventDec> = EventDec.fetchRequest()
if let results = try? context.fetch(fetchRequest) {
   for result in results {
     print("Status = \(result.eventStatus)")
   }
}

这假定您的 managedObjectContext 被称为上下文。 你也有一个错字eventStaus a 而不是eventStatus

【讨论】:

  • 刚刚意识到我自己的代码中的 仍在 fetchRequest 中。如果你把它改成let fetchRequest: NSFetchRequest&lt;EventDec&gt; = EventDec.fetchRequest() 有帮助吗?
  • 我试过了,它只是打印出 Status = /(result.eventStatus)
  • 对不起,我一直试图在 iPad 上回答这个问题。我希望现在笔记本电脑上的错别字更少。那行应该是print("Status = \(result.eventStatus)")
【解决方案2】:

好的,很高兴我在操场上检查了这一点,因为 Apple 在 Swift 3.0 中对子字符串进行了很多更改。试试这个,打印你的谓词的 Int 值(你也可以通过改变代码来访问这个值):

let index = fetchRequestDec.predicate.predicateFormat.index(fetchRequestDec.predicate.predicateFormat.endIndex, offsetBy: -1)
print("Status: \(Int(String(fetchRequestDec.predicate.predicateFormat[index]))!)")

【讨论】:

  • 'NSFetchRequest' 类型的值没有成员谓词格式
  • 哦,是的,对不起,该属性是一个 NSPredicate。我马上更新我的答案。
  • fetchRequestDec 应该是什么?因为我没有看到您涉及 eventStatus 属性。所以我得到零(致命错误)
  • 我正在使用你的 var 名称。 fetchRequestDec 有一个名为 predicate 的属性,它是一个 NSPredicate,根据这一行:我的 sn-p 的其余部分采用该字符串的最后一个字符并将其转换为 Int,然后打印它。我的 sn-p 中没有关于 eventStatus 的内容。这是你的格式字符串的一部分,我从最后开始数。你从哪里得到一个零值?
  • 感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-02
  • 2018-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-20
  • 2015-08-12
相关资源
最近更新 更多