【发布时间】:2019-09-11 16:20:31
【问题描述】:
在以下代码中,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
【问题讨论】:
标签: swift automatic-ref-counting deinit