执行被中断,原因:信号 SIGABRT

问题描述

我正在根据我正在学习的教程在操场上工作,并且我正在使用他们给我的文件(没有更改它)。不幸的是,我收到此错误“执行被中断,原因:信号 SIGABRT”。

这是我的代码错误出现在 people.filtered(using: allAge61)

class APerson: NSObject {    // Must inherit from NSObject or nspredicate will fail at runtime
    let name: String
    let age: Int 
    
    init(name: String,age: Int) {
        self.name = name
        self.age = age
    }
    
    // description lets you pretty print this class' instances in the sidebar
    override var description: String {
        return self.name + " - \(self.age) years old"
    }
}

/*:

and a bunch of People

*/

let groucho = APerson(name: "Groucho",age: 50)
let chicco  = APerson(name: "Chicco",age: 61)
let harpo   = APerson(name: "Harpo",age: 45)
let zeppo   = APerson(name: "Zeppo",age: 61)

let people: NSArray = [groucho,chicco,harpo,zeppo]
// using a NSArray here because predicates work with them,not with regular Swift Arrays

/*:

we can get __all people of age == 61__ with a simple predicate

*/

let allAge61 = nspredicate(format: "age = 61")

people.filtered(using: allAge61)

解决方法

NSPredicate 引用字符串“age”,但该类不符合“age”属性的键值编码。如果你让你的课程是这样的:

class APerson: NSObject {
    @objc let name: String
    @objc let age: Int

然后你就可以让它工作了。 KVC 是 Obj-C 运行时的功能,它允许您从像“age”这样的字符串转换为实际的年龄 getter/setter 方法,并且当它尝试解析字符串“age = 61”并将“age”转换为“年龄函数”,因为该属性没有被标记为@objc

或者全部使用 Swifty:

struct Person: CustomStringConvertible {
    let name: String
    let age: Int
    
    var description: String {
        "\(name) - \(age) years old"
    }
}

let groucho = Person(name: "Groucho",age: 50)
let chicco  = Person(name: "Chicco",age: 61)
let harpo   = Person(name: "Harpo",age: 45)
let zeppo   = Person(name: "Zeppo",age: 61)

let people = [groucho,chicco,harpo,zeppo]

people.filter { $0.age == 61 }