简体   繁体   中英

Weak/Strong Annotations for Non-Synthesized Properties in Objective-C

Since Objective-C 2.0 we have properties , a nice syntax for getting and setting values for instance variables. Since Clang 3.1 all properties which are not dynamic, not readonly with an explicit getter or don't have a custom getter and setter are automatically synthesized to ivars. And since ARC we have weak/strong annotations for properties which are used by ARC to define the memory management logic of automatically synthesized properties.

The properties still can be synthesized manually eg for a readonly property backed by an ivar and returning a default value, for instance.

Sometimes, properties are also useful if they are not synthesized at all. I have found a few use cases when I use this sort of behavior:

  • A custom getter and setter which use a custom ivar for storing the actual value and which perform some additional actions.
  • A dynamic property, eg in subclasses of NSManagedObject .
  • A readonly property which simply passes through a property of an object stored in another property (eg a private one).

The Question: Does it makes sense to annotate these non-synthesized properties with weak/strong according to their actual usage or not? What is the best practice?

( https://twitter.com/kubanekl/status/427142577310408704 )

I would say the answer is yes , even if only for documentation sake.

Even if you do not use any of the compiler and framework related default implementations, and implement everything by yourself, someone attempting to use these properties will be in much better position of understanding the API if he is able to get a hint on how the memory management would behave. A person does not really have to know how a setter or a getter is implemented internally, but he would might have to know, for example, if after calling a setter, the value was copied or retained or just assigned, and implement his side of things accordingly.

Yes, it does.

The property definition is a contract specification. Just because the compiler isn't fulfilling the contract doesn't mean you shouldn't respect it when manually implementing the accessor methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM