2

I'm just updating a really old project to ARC (2017 – I know).

I've noticed that for readonly property declarations, it's adding a weak decorator. Eg:

// Before conversion to ARC:
@property (nonatomic, readonly) NSString *defaultName;

// After conversion to ARC:
@property (weak, nonatomic, readonly) NSString *defaultName;

Could someone explain why it's doing this?

There are a few SO questions and answers about the meaning of weak, strong and copy when applied to a readonly property. An example is this which seems to be directly contradicted by this – I don't really see how it makes sense as they only seem to apply on setting a property and a readonly has an explicit getter method.

Benjohn
  • 13,228
  • 9
  • 65
  • 127

1 Answers1

2

Before the introduction of ARC, the default memory attribute was assign, therefore

@property (nonatomic, readonly) NSString *defaultName;

was the same as

@property (nonatomic, assign, readonly) NSString *defaultName;

That should explain you why ARC migration uses weak.

This changed when ARC was introduced - for object types strong/retain became the default.

This attribute affects only the setters anyway, therefore for readonly properties the attribute can have any value.

Benjohn
  • 13,228
  • 9
  • 65
  • 127
Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • Thanks for answering on something of fairly minimal interest to most readers now! It makes sense that it picks `weak` because there's no other specifier given and this is the default, thanks. So, in the case of `readonly`, the ARC converter could just leave it out the memory attribute, but doesn't. Specifying it is redundant, but not problematic? – Benjohn Aug 04 '17 at 13:31
  • 1
    @Benjohn It could not leave out the attribute because that could be wrong (`assign` was the old default, the new default is `strong`). The property could be overwritten somewhere as `readwrite` and then the memory attribute would have to be the same... – Sulthan Aug 04 '17 at 13:46
  • That makes sense. Good answer – adev Aug 06 '17 at 02:09