问题
I never use ivars. I only use properties -- sometimes assign properties with primitive types, and sometimes on a "private" class extension. I've seen the advantages of not using ivars in switching to ARC -- I have some borrowed code with lots of ivars that I still can't "ARC", since I don't know what needs to be retained. So I know some advantages of not using ivars, but what are the advantages of using ivars instead of properties?
Note: I depend exclusively on the ivars that are automagically added in (by the compiler?) for the property declaration.
Don't mark to close: I've looked at some of the other questions, like this and this and none hit the spot. The titles look good, but like so many questions on SO, the questions are a mess of strange doubts and other stuff.
回答1:
Declared properties cannot be treated in the same manner as an @protected
ivar. You can declare the property in a class extension to keep it private from any other class, or declare it in the header interface to make it publicly accessible, however there is no way to make it accessible only to subclasses. This would require the ivar declaration.
EDIT
Just another brief thought. I have recently been writing a lot of framework classes, and I think there might be something to be said for using iVars as documentation.
For example, let's say you are calling some code in a tight loop and you want to ensure that it is performant. Inside that tight loop you want to access a property of a class, but need to know whether each time you call it the return value is calculated on-the-fly or stored in an iVar. Seeing the iVar in the header is a quick way to ensure that you'll get that variable back without much overhead.
回答2:
I don't see any reason to use iVars if you don't have to. If Apple and the compiler want to do work for you, I say let them. You'll have code that more efficient and easier to maintain. At this point iVars are legacy code.
回答3:
One good reason for me: an annoying GCC bug, see this other question for a description.
If you're using Clang/LVVM, then you don't have to worry about this bug.
来源:https://stackoverflow.com/questions/7418858/no-ivars-what-am-i-missing