我试图对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)”
答案 0 :(得分:3)
objc_getAssociatedObject
将返回nil
到NSDate
,然后强制转换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
仅用作内存地址
唯一地标识关联对象。那个内容
静态属性及其类型是无关紧要的,根本不使用。特别是,对象关联不是初始化的"具有该属性的值。