Hacker News new | ask | show | jobs
by xenadu02 2687 days ago
> I had a weak reference which was turning nil (Swift weak references are zeroing), and I couldn't figure out why

This is extremely unlikely. If zeroing weak references were broken a lot of macOS/iOS would be broken. You probably have a bug or the memory just hasn't been overwritten yet, but the retain count is actually zero, you overwrote the reference, or something similar.

Turn on Zombie Objects in Xcode then try it again. Objects are never deallocated but will turn into an instance of NSZombie when their refcount reaches zero. See if your supposedly "still alive" object is actually an NSZombie at that point.

> I wrap a lot of my GCD code in extra locks ... Without them, it occasionally crashes with strange memory errors that are impossible to figure out

You definitely have some race conditions or other concurrency bugs then. Common issues include being on a different queue than you expected (use dispatchPrecondition() to verify), being on a concurrent queue when you expected a serial queue, failure to use a barrier block on a concurrent queue (another good case where dispatchPrecondition() can help you), or accessing something both on and off the queue.

1 comments

Weak references turning nil is perfectly expected.

But you should never access a weak reference. When you need to access a weak reference, you should attempt to take a strong reference. That will either fail, and should be handled, or will succeed, and then will not be nil, and won't 'turn nil'.