ios - objective-C : Weak attritube don't work as expected

标签 ios weak-references strong-references

<分区>

Possible Duplicate:
Why do weak NSString properties not get released in iOS?

我是 Objective C 的新手,我有一些我自己无法回答的问题。 我有一段代码用于测试 __weak 变量(当然我使用的是 ARC):

NSString *myString = [[NSString alloc] initWithFormat:@"John"];
NSString * __weak weakString = myString;
myString = nil; //<-- release the NSString object
NSLog(@"string: %@", weakString);

上面代码的输出符合预期,因为 weakString 是一个弱变量:

2013-01-02 11:42:27.481 ConsoleApp[836:303] string: (null)

但是当我将代码修改为:

NSString *myString = [[NSString alloc] initWithFormat:@"John"];
NSString * __weak weakString = myString;
NSLog(@"Before: %@", weakString); //<--- output to see if the __weak variable really works.
myString = nil;
NSLog(@"After: %@", weakString);

输出完全不是我所期望的:

2013-01-02 11:46:03.790 ConsoleApp[863:303] Before: John
2013-01-02 11:46:03.792 ConsoleApp[863:303] After: John

后者的 NSLog 的输出一定是 (nil) 而不是“John”。我尝试在许多文档中进行搜索,但没有找到此案例的答案。 有人可以给出合理的解释吗?提前致谢。

最佳答案

NSLog 函数将传递的 NSString 保留在自动释放池中。因此,在自动释放池耗尽之前,归零弱变量不会被归零。例如:

__weak NSString* weakString = nil;

@autoreleasepool {
    NSString* myString = [[NSString alloc] initWithFormat:@"Foo"]; // Retain count 1
    weakString = myString;         // Retain count 1
    NSLog(@"A: %@", weakString);   // Retain count 2
    NSLog(@"B: %@", weakString);   // Retain count 3
    myString = nil;                // Retain count 2
    NSLog(@"C: %@", weakString);   // Retain count 3

    NSAssert(weakString != nil, @"weakString is kept alive by the autorelease pool");
} 

// retain count 0
NSAssert(weakString == nil, @"Autorelease pool has drained.");

为什么 NSLog 将字符串放入自动释放池中?这是一个实现细节。

您可以使用调试器或 Instruments 来跟踪 NSString 实例的保留计数。确切的保留计数并不重要,但它确实揭示了幕后发生的事情。重要的是当自动释放池被耗尽时,NSString 实例被释放。

关于ios - objective-C : Weak attritube don't work as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14116993/

相关文章:

ios - 在Windows中无法以编程方式在iOS中录制的音频无法播放

ios - 响应 child 和 parent 的触摸事件

Swift 弱变量行为差异?

python-2.7 - 如何将弱引用更改为强引用?

IOS关于弱和强,结果应该是什么?并不断声明

ios - UITextField 触摸时崩溃

objective-c - __weak 和 __block 引用有什么区别?

java - 使用 Wea​​kReference 的 Java 示例的线程安全

objective-c - iOS 中的__weak 和__strong 属性有什么区别?

ios - Swift - 使用 XCTest 测试包含闭包的函数