Swift扩展异常执行被中断,原因:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)

时间:2016-06-26 19:17:28

标签: ios swift nsdate swift-extensions exc-bad-instruction

我试图对NSDate进行扩展。我想要的是一个标志,指示是否必须在以后删除NSDate

所以我在游乐场试过这个

//: Playground - noun: a place where people can play

import UIKit

var str = "Hello, playground"



extension NSDate {
    private struct RemovalInformation {
        static var removed: Bool = false
    }
    var removed: Bool {
        get {
            return (objc_getAssociatedObject(self, &RemovalInformation.removed) as! Bool)
        }
        set(newValue) {
            objc_setAssociatedObject(self, &RemovalInformation.removed, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }
}

let date = NSDate()
print( "The Date is: \(date)")

if(date.removed == true) {
    print ("removed")
}

但是行if(date.removed == true)产生错误我不知道如何处理:“EXC_BAD_INSTRUCTION(code = EXC_I386_INVOP,subcode = 0x0)”

enter image description here

1 个答案:

答案 0 :(得分:3)

如果没有关联对象,

objc_getAssociatedObject将返回nilNSDate,然后强制转换as! Bool崩溃。 (如果设置了关联对象,它也会崩溃,但它会 值不可转换为Bool。)

您可以将该属性设为可选:

var removed: Bool? {
    get {
        return objc_getAssociatedObject(self, &RemovalInformation.removed) as? Bool
    }
    set(newValue) {
        objc_setAssociatedObject(self, &RemovalInformation.removed, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
    }
}

或提供默认值,例如使用nil-coalescing运算符??

var removed: Bool {
    get {
        return objc_getAssociatedObject(self, &RemovalInformation.removed) as? Bool ?? false
    }
    set(newValue) {
        objc_setAssociatedObject(self, &RemovalInformation.removed, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
    }
}

请注意,&RemovalInformation.removed仅用作内存地址 唯一地标识关联对象。那个内容 静态属性及其类型是无关紧要的,根本不使用。特别是,对象关联不是初始化的"具有该属性的值。