-2

在以下代码中NSString,并且NSNumber 在删除引用时不会取消初始化。NSMutableString并且NSAttributedString被取消初始化。deinit 的标准是什么?

class WeakHolder<R : AnyObject> {
    weak var cheez : R?
    init(_ _cheez : R) {
        cheez = _cheez
    }
}

do {
        var nsStringCollection = [NSString(string: "77"),NSString(string: "99")]
        let weakNSStringHolder = WeakHolder(nsStringCollection[1])
        nsStringCollection.removeLast()
        print("NSString : \(weakNSStringHolder.cheez)")
    }

    do {
        var nsMutableStringCollection = [NSMutableString(string: "77_m"),NSMutableString(string: "99_m")]
        let weakNSMutableStringHolder = WeakHolder(nsMutableStringCollection[1])
        nsMutableStringCollection.removeLast()
        print("NSMutableString : \(weakNSMutableStringHolder.cheez)")
    }

    do {
        var nsNumberCollection = [NSNumber(integerLiteral: 77),NSNumber(integerLiteral: 99)]
        let weakNumberHolder = WeakHolder(nsNumberCollection[1])
        nsNumberCollection.removeLast()
        print("Number : \(weakNumberHolder.cheez)")
    }

    do {
        var nsAttributedCollection = [NSAttributedString(string: "77_atts"),NSAttributedString(string: "99_atts")]
        let weakAttributedHolder = WeakHolder(nsAttributedCollection[1])
        nsAttributedCollection.removeLast()
        print("AttrString : \(weakAttributedHolder.cheez)")
    }

输出 :

NSString : Optional(99)
NSMutableString : nil
Number : Optional(99)
AttrString : nil
4

1 回答 1

1

NSString对象直接存储在它们的(标记的)指针中,不需要内存管理。其他静态字符串存储在二进制文件中,可能永远不会被释放。既不分配内存,所以也不必须释放它。

NSMutableStringNSAttributedString分配实际对象,因此它们还需要释放它们。

这两种行为都是实现细节,你不应该依赖它们。他们没有得到承诺。

内存管理的规则是对你关心的任何事情都持有强引用,当你不再关心它时,删除你的强引用。应该只清理内存(例如,如果需要,deinit调用malloc 块)。free没有“业务逻辑”应该在deinit; 没有保证它会运行。(例如,在正常程序终止期间,deinit会跳过,与 C++ 不同。)

于 2019-04-22T14:27:31.590 回答