我有点固执,但我想知道好强和弱引用,所以这就是为什么我在问你一次。
试想一下:
__weak NSString* mySecondPointer = myText;
NSLog(@"myText: %@", myText);
其结果是myText: (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"];
弱指针的值没有改变为零(为什么一开始仍然存在于内存中,尽管它没有任何强烈的裁判创建的对象 - ?也许它有)
我已尝试之一:(但不利于添加注释,我想)。 我已经包括在那里,我创造了一个@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)