【问题标题】:Swift: How do I create a predicate with an Int value?Swift:如何创建具有 Int 值的谓词?
【发布时间】:2015-10-31 07:40:09
【问题描述】:

我在此语句中收到 EXC-BAD-ACCESS 错误:

var thisPredicate = NSPredicate(format: "(sectionNumber == %@"), thisSection)

thisSection 的 Int 值为 1,当我将鼠标悬停在它上面时显示值 1。但是在调试区域我看到了这个:

thisPredicate = (_ContiguousArrayStorage ...)

另一个使用字符串的谓词显示为 ObjectiveC.NSObject 为什么会这样?

【问题讨论】:

  • 你有一个额外的左括号,不应该在那里
  • 我不知道为什么它会在上面显示一个额外的括号,因为那不是我所拥有的 - 这是: var thisPredicate = NSPredicate(format: "(sectionNumber == %@)",thisSection)
  • @PatriciaW 你的问题是你错过了 @ 之后的闭括号。顺便说一句,我已经编辑了我之前的答案,也许你应该看看我添加的一些注意事项。
  • 雨果,我在上面的评论中更正了我的代码,但我没有编辑它......我现在会这样做。

标签: swift core-data xcode6


【解决方案1】:

当您的数据安全或经过清理后,您可以尝试字符串插值Swift Standard Library Reference。看起来像这样:

let thisSection = 1
let thisPredicate = NSPredicate(format: "sectionNumber == \(thisSection)")

【讨论】:

【解决方案2】:

您需要将%@ 更改为%i 并删除多余的括号:

这里的主要问题是您将Int 放置在期望String 的位置。

这是一个基于post的示例:

class Person: NSObject {
    let firstName: String
    let lastName: String
    let age: Int

    init(firstName: String, lastName: String, age: Int) {
        self.firstName = firstName
        self.lastName = lastName
        self.age = age
    }

    override var description: String {
        return "\(firstName) \(lastName)"
    }
}

let alice = Person(firstName: "Alice", lastName: "Smith", age: 24)
let bob = Person(firstName: "Bob", lastName: "Jones", age: 27)
let charlie = Person(firstName: "Charlie", lastName: "Smith", age: 33)
let quentin = Person(firstName: "Quentin", lastName: "Alberts", age: 31)
let people = [alice, bob, charlie, quentin]


let thisSection = 33
let thisPredicate = NSPredicate(format: "age == %i", thisSection)

let _people = (people as NSArray).filteredArrayUsingPredicate(thisPredicate)
_people

另一种解决方法是将thisSection 的值设为String,这可以通过字符串插值 或通过descriptiondescription 属性来实现@ .. 假设:

变化:

let thisPredicate = NSPredicate(format: "age == %i", thisSection)

let thisPredicate = NSPredicate(format: "age == %@", thisSection.description)

let thisPredicate = NSPredicate(format: "age == %@", "\(thisSection)")

当然,你总是可以绕过这一步,选择更硬编码(但也是正确的)的东西:

let thisPredicate = NSPredicate(format: "sectionNumber == \(thisSection)")

但是考虑到一些奇怪的原因 字符串插值这种结构:"\(thisSection)")导致保持循环,如here所述

【讨论】:

  • 雨果,感谢您的这些建议。我尝试了 %@,但不知道使用 .description。我尝试了 %d 但没有尝试 %i。
  • .descriptionSwift 中每种数据类型的属性,它将NumberDate 等的值转换为String 表示形式。 %i 为您进行此转换。
  • 花两天时间弄清楚为什么我的带有谓词的 fetchedresultcontroller 不起作用,解决方案是将 %@ 替换为 %i。数据类型很重要,我们需要确保我们使用正确的类型进行过滤!!!
  • 如果值是 int64 这将不起作用%我将转换将其视为 int32,如果值高于 2,147,483,648 它将溢出。
【解决方案3】:

在 64 位架构上,Int 映射到 Int64,如果其值大于 2,147,483,648,%i 将溢出。

您需要将 %@ 更改为 %ld 并删除多余的括号。

【讨论】:

  • 那我们应该用什么??
猜你喜欢
  • 2015-09-07
  • 2011-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-01
相关资源
最近更新 更多