Ios 为什么带有弱限定符的变量会保留一个对象?
这是我的密码:Ios 为什么带有弱限定符的变量会保留一个对象?,ios,automatic-ref-counting,weak-references,Ios,Automatic Ref Counting,Weak References,这是我的密码: extern void _objc_autoreleasePoolPrint(); int main(int argc, const char * argv[]) { NSArray __weak *tmp = nil; @autoreleasepool { NSArray __strong *obj = [[NSArray alloc] init]; NSLog(@"obj &: %p", obj);
extern void _objc_autoreleasePoolPrint();
int main(int argc, const char * argv[])
{
NSArray __weak *tmp = nil;
@autoreleasepool {
NSArray __strong *obj = [[NSArray alloc] init];
NSLog(@"obj &: %p", obj);
tmp = obj;
NSLog(@"tmp &: %p", tmp);
_objc_autoreleasePoolPrint();
}
NSLog(@"tmp: %@", tmp); // why not (null) ?
return 0;
}
和控制台输出:
2013-05-01 22:14:32.966 SimpleConsoleObjectiveCApplicationWithARC[40660:f07] obj &: 0x7fedf9403110
2013-05-01 22:14:32.969 SimpleConsoleObjectiveCApplicationWithARC[40660:f07] tmp &: 0x7fedf9403110
objc[40660]: ##############
objc[40660]: AUTORELEASE POOLS for thread 0x7fff751af180
objc[40660]: 2 releases pending.
objc[40660]: [0x7fedf9805000] ................ PAGE (hot) (cold)
objc[40660]: [0x7fedf9805038] ################ POOL 0x7fedf9805038
objc[40660]: [0x7fedf9805040] 0x7fedf9403110 __NSArrayI
objc[40660]: ##############
2013-05-01 22:14:32.971 SimpleConsoleObjectiveCApplicationWithARC[40660:f07] tmp: (
)
PS#1
将NSArray更改为NSMutableArray,tmp变量变为零
extern void _objc_autoreleasePoolPrint();
int main(int argc, const char * argv[])
{
NSMutableArray __weak *tmp = nil;
@autoreleasepool {
NSMutableArray __strong *obj = [[NSMutableArray alloc] init];
NSLog(@"obj &: %p", obj);
tmp = obj;
NSLog(@"tmp &: %p", tmp);
_objc_autoreleasePoolPrint();
}
NSLog(@"tmp: %@", tmp);
return 0;
}
有人能解释一下为什么会这样吗?似乎
[[NSArray alloc]init]
返回空NSArray
的“共享实例”:
NSArray *a = [[NSArray alloc] init];
NSArray *b = [[NSArray alloc] init];
NSLog(@"a &: %p", a);
NSLog(@"b &: %p", b);
输出:
a &: 0x100103110
b &: 0x100103110
a&:0x100103110
b&:0x100103110
即使您的强引用对象消失,该“共享实例”仍将继续存在,
因此,弱指针未设置为nil
显然,
[[NSMutableArray alloc]init]
无法返回共享实例。Martin R,是的,所有不可变类都返回“共享实例”(已检查NSString、NSDictionary等),但是否有任何方法可以传递此“功能”?@AndrewShmig:您试图实现什么?为什么需要弱引用变为nil?Martin R,我正在试图理解为什么在变量obj离开其作用域后uu-weak不能按预期工作。@AndrewShmig:如果弱指针指向的对象被销毁,而不是指向该对象的指针离开作用域,则弱指针将被设置为nil。NSArray类保留自己的指向共享实例的强指针,因此即使您的指针obj离开范围,对象也不会被销毁。