1

我试图对 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)”

在此处输入图像描述

4

1 回答 1

3

objc_getAssociatedObjectnil如果没有对象与 关联,则返回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仅用作唯一标识关联对象的内存地址。该静态属性的内容及其类型是无关紧要的,根本不使用。特别是,对象关联不会使用该属性的值“初始化”。

于 2016-06-26T19:26:31.047 回答