Can I have a static pointer that is weak in objective-c? I know it compiles, but I want to know if it will behave as I expect a weak pointer to behave.
我可以在objective-c中使用弱的静态指针吗?我知道它编译,但我想知道它是否会像我期望的弱指针行为一样。
__weak static HMFSomeClass *weakStaticPointer;
1 个解决方案
#1
16
Yes, that behaves like a proper weak pointer:
是的,这表现得像一个适当的弱指针:
__weak static NSObject *weakStaticPointer;
int main(int argc, char * argv[])
{
@autoreleasepool {
NSObject *obj = [NSObject new];
weakStaticPointer = obj;
NSLog(@"%@", weakStaticPointer);
obj = nil; // object is deallocated -> weak pointer is set to nil
NSLog(@"%@", weakStaticPointer);
}
return 0;
}
Output:
<NSObject: 0x100106a50>
(null)
Also I cannot find any restrictions in the Clang/ARC documentation that forbids a weak pointer to be static.
另外,我在Clang / ARC文档中找不到任何禁止弱指针为静态的限制。
#1
16
Yes, that behaves like a proper weak pointer:
是的,这表现得像一个适当的弱指针:
__weak static NSObject *weakStaticPointer;
int main(int argc, char * argv[])
{
@autoreleasepool {
NSObject *obj = [NSObject new];
weakStaticPointer = obj;
NSLog(@"%@", weakStaticPointer);
obj = nil; // object is deallocated -> weak pointer is set to nil
NSLog(@"%@", weakStaticPointer);
}
return 0;
}
Output:
<NSObject: 0x100106a50>
(null)
Also I cannot find any restrictions in the Clang/ARC documentation that forbids a weak pointer to be static.
另外,我在Clang / ARC文档中找不到任何禁止弱指针为静态的限制。