我有点顽固,但我想了解弱弱和强烈的参考,所以这就是为什么我再次问你.
考虑一下:
__weak NSString* mySecondPointer = myText;
NSLog(@"myText: %@", myText);
Run Code Online (Sandbox Code Playgroud)
结果是myText: (null)非常明显的 - 弱引用在赋值后设置为null,因为没有对尖头对象的强引用.
但在这种情况下:
__strong NSString* strongPtr = [[NSString alloc] initWithFormat:@"mYTeSTteXt %d"];
// weak pointer points to the same object as strongPtr
__weak NSString* weakPtr = strongPtr;
if(strongPtr == weakPtr)
NSLog(@"They are pointing to the same obj");
NSLog(@"StrongPtr: %@", strongPtr);
NSLog(@"weakPtr: %@", weakPtr);
NSLog(@"Setting myText to different obj or nil");
// after line below, there is no strong referecene to the created object:
strongPtr = [[NSString alloc] …Run Code Online (Sandbox Code Playgroud) weak-references reference-counting objective-c strong-references
如果我有一段看起来像这样的代码:
- (void)testSomething
{
__weak NSString *str = [[NSString alloc] initWithFormat:@"%@", [NSDate date]];
NSLog(@"%@", str);
}
Run Code Online (Sandbox Code Playgroud)
输出将为(null),因为没有对str的强引用,它将在我分配后立即释放.这是有道理的,并在"过渡到ARC"指南中详细说明.
如果我的代码如下所示:
- (void)testSomething
{
__weak NSString *str = [NSString stringWithFormat:@"%@", [NSDate date]];
NSLog(@"%@", str);
}
Run Code Online (Sandbox Code Playgroud)
然后它正确打印出当前日期.显然你会期望它在非ARC世界中工作,因为它str会被自动释放,因此在此方法退出之前有效.但是,在启用ARC的代码中,人们通常认为两种形式(stringWithFormat&alloc/initWithFormat)是等价的.
所以我的问题是,第二个例子的代码是否可以保证在ARC下工作.也就是说,如果我有一个弱引用的对象,我通过什么我们通常会考虑一个自动释放便捷构造得到的,是它保证是安全的使用该引用在同一范围内,我通常会对没有ARC(即,直到方法退出)?
我编写了以下示例代码以了解ARC的工作原理
@property (nonatomic, weak) NSString *myString;
@property (nonatomic, weak) NSObject *myObj;
@end
@implementation ViewController
@synthesize myString = _myString;
@synthesize myObj = _myObj;
- (void) viewDidAppear:(BOOL)animated
{
NSLog(@"Appearing Obj: !%@!",self.myObj);
NSLog(@"Appearing String: !%@!",self.myString);
}
- (void)viewDidLoad
{
self.myObj = [[NSObject alloc] init];
self.myString = [[NSString alloc] init];
NSLog(@"Loading Obj %@",self.myObj);
NSLog(@"Loading String: !%@!",self.myString);
}
Run Code Online (Sandbox Code Playgroud)
但令人惊讶的是我得到了这些结果:
2012-06-19 15:08:22.516 TESTER[4041:f803] Loading Obj (null)
2012-06-19 15:08:22.517 TESTER[4041:f803] Loading String: !!
2012-06-19 15:08:22.533 TESTER[4041:f803] Appearing Obj: !(null)!
2012-06-19 15:08:22.535 TESTER[4041:f803] Appearing String: !!
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,Obj被正确释放但我的字符串(也是一个弱属性)不会打印出null ...为什么不呢?