首页 > 解决方案 > 执行被中断,原因:信号 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)

标签: swiftsigabrt

解决方案


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 }

推荐阅读