How to zeroing weak references under non-ARC?

2019-06-21 03:19发布

问题:

I don't like ARC.

But the most important feature of ARC, zeroing weak reference, is missing under non-ARC. Currently I'm using MAZeroingWeakRef, it works, but hacky, sometimes makes codes redundant. Any other ways for zeroing weak references?

回答1:

Implementing zeroing weak reference is not hard. All what you have to do is just tracking all referencing pointers - store them in a collection - and assigning NULL when pointing object is being deallocated. Anyway, doing all these things manually is really a lot of work, you literally need to write all manual tracking code to be efficient enough in Objective-C.

And at the end, you will finally discover you need some automatic code writing machine - static compiler - and that's exactly what ARC does. You could implement something like ARC yourself. But If I am you, I will just use already existing, robust, stable, well-designed and supported implementation by compiler maintainer.

Also, not following Apple is not wise behavior if you want to develop Apple-stuffs. Unlike other platform holders - such as Microsoft -, Apple doesn't care much about keeping backward compatibility. If they don't think something is good, it will be deprecated and removed eventually - like Objective-C GC.



回答2:

I think you should stick to the paradigm Apple itself recommended before ARC was introduced, that is, nil-ing all of your "weak" references from within the -dealloc method. Not only it is a de facto standard, but it also is the way the Xcode code refactor behaves when ARC is not enabled, so conforming to it should save you a couple headaches.