5

Should one use

@property (nonatomic, weak, readonly)

or

@property (nonatomic, readonly)?

Weak has the advantage of nil-ing out the instance if it gets deallocated, but is readonly implying weak? Should one explicit declare a property as weak if it want the weak behaviour?

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
Meda
  • 2,776
  • 4
  • 20
  • 31

2 Answers2

5

If you want to keep a pointer to an object that you don't own but want it to be valid only as long as it exists, then you want to use a weak pointer because when it gets deallocated by the owner, your pointer will automatically get set to nil and won't be pointing to memory that it shouldn't be.


These both have differnect meaning, readonly doesn't make any differnce if it is weak or strong.

@property (nonatomic, weak, readonly)
@property (nonatomic, readonly)

You can also find some reference here.

Community
  • 1
  • 1
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
  • 3
    to add to @AnoopVaidya's answer readonly simply tells the compiler to only generate a getter, not a setter. It also handily gives you a nice warning if you do try to change that property directly. – JiuJitsuCoder Mar 06 '13 at 18:31
2

Weak or strong is by no means related to readonly or readwrite. None implies the other.

A strong relation takes ownership. A weak does not but it receives the service of being nullified upon deletion of the related object.

Readonly suppresses a setter (afaik). The property cannot be changed from outside its class. Readwrite (wich is the default if none is stated) allows changes to the property.

That's basically it. That are two settings which are not related to each other. They work in all thinkable comibnations.

Hermann Klecker
  • 14,039
  • 5
  • 48
  • 71