Swift:某些类未初始化

时间:2019-04-22 13:13:27

标签: swift automatic-ref-counting deinit

在以下代码中,删除引用后,NSStringNSNumber不会被初始化。 NSMutableStringNSAttributedString被取消初始化。 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

1 个答案:

答案 0 :(得分:1)

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

NSMutableStringNSAttributedString分配实际对象,因此它们也需要取消分配它们。

这两种行为都是实现细节,您不应依赖它们。他们没有答应。

内存管理的规则是对您关心的所有内容保持强引用,并在不再关心它时删除您的强引用。 deinit仅应清除内存(例如,如有必要,请在malloc块上调用free)。 deinit中不应包含“业务逻辑”;没有保证它将永远运行。 (例如,在正常程序终止期间,deinit被跳过,这与C ++不同。)