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.
__weak static HMFSomeClass *weakStaticPointer;
No, it will be initialized to the NULL pointer value, whether or not its representation is zero. For pointers, the constant 0 transforms to the NULL pointer value, not the bit pattern of all zeros.
A static pointer can be used to implement a function that always returns the same buffer to the program. This can be helpful in serial communication.
To declare a pointer to a static member of the class data, you simply need to declare a pointer to the data type that has a static data member. Then, this pointer needs to be assigned the static member address of the object data of this class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With