我有点固执,但我想要很好地理解弱引用和强引用,这就是为什么我再次向你请教的原因。
考虑以下情况:
__weak NSString* mySecondPointer = myText;
NSLog(@"myText: %@", myText);
结果是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] initWithString:@"abc"]; // or myText=nil;
if(strongPtr == weakPtr)
NSLog(@"Are the same");
else
NSLog(@"Are NOT the same");
NSLog(@"StrongPtr: %@", strongPtr);
// Why weak pointer does not point to nul
NSLog(@"weakPtr: %@", weakPtr);
输出:
2013-03-07 09:20:24.141 XMLTest[20048:207] They are pointing to the same obj
2013-03-07 09:20:24.142 XMLTest[20048:207] StrongPtr: mYTeSTteXt 3
2013-03-07 09:20:24.142 XMLTest[20048:207] weakPtr: mYTeSTteXt 3
2013-03-07 09:20:24.143 XMLTest[20048:207] Setting myText to different obj or nil
2013-03-07 09:20:24.143 XMLTest[20048:207] Are NOT the same
2013-03-07 09:20:24.144 XMLTest[20048:207] StrongPtr: abc
2013-03-07 09:20:24.144 XMLTest[20048:207] weakPtr: mYTeSTteXt 3 // <== ??
我的问题:
为什么在 strongPtr = [[NSString alloc] initWithString:@"abc"];
之后,弱指针的值没有更改为 nil(为什么一开始创建的对象仍然存在于内存中,尽管它没有任何强引用?--或许它有吗?)
我尝试了这个解决方法:(但我不确定是否适合添加注释)。我已经在 @autorealesepool 中包含了创建 strongPtr 的代码。我不确定它是否是正确的解决方案,但它可以正常工作...
__strong NSString* strongPtr;
__weak NSString* weakPtr;
@autoreleasepool {
strongPtr = [[NSString alloc] initWithFormat:@"mYTeSTteXt %d", 3];
// weak pointer point to object create above (there is still strong ref to this obj)
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] initWithString:@"abc"];
}
if(strongPtr == weakPtr)
NSLog(@"Are the same");
else
NSLog(@"Are NOT the same");
NSLog(@"StrongPtr: %@", strongPtr);
// Why weak pointer does not point to nul
NSLog(@"weakPtr: %@", weakPtr);
输出:
2013-03-07 09:58:14.601 XMLTest[20237:207] They are pointing to the same obj
2013-03-07 09:58:14.605 XMLTest[20237:207] StrongPtr: mYTeSTteXt 3
2013-03-07 09:58:14.605 XMLTest[20237:207] weakPtr: mYTeSTteXt 3
2013-03-07 09:58:14.606 XMLTest[20237:207] Setting myText to different obj or nil
2013-03-07 09:58:14.607 XMLTest[20237:207] Are NOT the same
2013-03-07 09:58:14.607 XMLTest[20237:207] StrongPtr: abc
2013-03-07 09:58:14.608 XMLTest[20237:207] weakPtr: (null)
if(strongPtr == weakPtr)
和NSLog(@"weakPtr: %@", weakPtr);
两段代码似乎都会创建临时/自动释放的引用。如果你移除这些行,那么在结尾处weakPtr
会被设为nil
,与预期相符。 - Martin R