13

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;
Hackmodford
  • 3,901
  • 4
  • 35
  • 78
  • you can test it easily why don't you try it? and I can't see any reason why it may failed (then it shouldn't compile without warning). – Bryan Chen Jan 15 '14 at 21:07
  • I think it will behave as expected, if you assign it to an object, you will be able to access the object through this static pointer as long as that object is retained elsewhere. – Jack Jan 15 '14 at 21:08
  • Any particular reason you would like to have a weak static pointer? – Unheilig Jan 15 '14 at 21:18
  • TextEdit has a weak static pointer. I think it's a pointer to the most-recently opened document. – Greg Parker Jan 15 '14 at 21:45
  • @Unheilig I comment on the accepted answer one really terrible use-case that might be of interest. – Dan Rosenstark Jan 06 '16 at 20:12

1 Answers1

21

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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 1
    Thanks, this is great for the use-case where you have no idea why your object is not being dealloc'ed. This way you get to reuse one instance instead of leaking a new instance with each use. Maintaining a weak-static variable is a silly temporary fix and not a solution, of course. Thx! – Dan Rosenstark Jan 06 '16 at 20:12