Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a weak static pointer?

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;
like image 369
Hackmodford Avatar asked Jan 15 '14 21:01

Hackmodford


People also ask

Is static pointer initialized to null?

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.

What is the use of static pointer?

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.

Can we assign pointer to a static variable?

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.


1 Answers

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.

like image 121
Martin R Avatar answered Sep 30 '22 03:09

Martin R