SWIFT:如何使用Int值创建谓词?

时间:2015-08-07 19:00:04

标签: swift core-data xcode6

我希望没有人告诉我RTFM,因为我在这里和Apple Developer上一直在努力解决这个问题并进行大量搜索。

我在此声明中收到EXC-BAD-ACCESS错误:

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

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

thisPredicate = (_ContiguousArrayStorage ...)

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

3 个答案:

答案 0 :(得分:29)

您可以尝试使用String Interpolation Swift Standard Library Reference。这看起来像这样:

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

答案 1 :(得分:21)

您需要为%@更改%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,这可以通过{{>> String Interpolation 或description Int属性实现。 1}} ..让我们说:

更改:

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

答案 2 :(得分:0)

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

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