Is it safe to declare all properties to weak to avoid reference count overhead?
This is problematic on two counts. First, weak
doesn't avoid reference counting. It actually performs more bookkeeping than strong
. See Lots of overhead for weak property? for a good discussion of that.
Next, this is wrong because weak
and strong
mean different things that cannot be interchanged. As MartinM notes, if you make your properties weak
, they'll just disappear as soon as you assign them if nothing else is holding onto them.
If not safe then why it's not safe?
It is totally safe. It just won't work. Your program will have well defined behavior, and shouldn't crash due to marking all your properties weak
. Most of your properties will just be nil
. If you used unsafe_unretained
instead of weak
, then you would avoid some reference counting overhead, and your program would typically crash (because the objects would still be destroyed, the pointers would just become invalid).
What will be the reference count of str?
That is not a meaningful question, even though it feels like one. In this particular case the answer is 9,223,372,036,854,775,807 because that's always the retain count of a static string, because static strings cannot be destroyed and ignore retain/release calls. (That value is NSNotFound
in ObjC. I believe this used to return 1,152,921,504,606,846,975, but my tests indicate it's changed.)
But in the general case, it could be anything at this point in time. And what it is at this point in time versus at the end of the event loop (when the autoreleasepool drains) could be dramatically different. Do not chase retain count values. They will always lie to you. Create strong references to things you care about. Create weak references only when you need them for their specialized purposes.
Retain counts are an internal implementation detail. Before ARC, they were misleading to the point of uselessness. Since ARC, they're like asking "what assembly instructions will this compile to." It's important, but it depends on everything else about the program and how it's compiled.
If you have a specific performance problem related to memory management, then there are techniques for dealing with that in a case-by-case basis, and StackOverflow can help you. But ARC is extremely good at optimizing memory management. Let it do its job.