0

How to quickly know which attribute to add to a @property ?

I got it for @property (strong) and @property (weak), I think : strong if the class "owns" the referred-to instance ; weak if it is just a reference to an object whose existence is not managed to our current class.

If the property is created by dragging-and-dropping from Interface Builder, sometimes there is the cryptic unretain_unsafe or so. It sounds so complicated to me, but I believe Xcode knows what it does...

  • I also kind of understand that retain, assign are kind of deprecated...

  • And that it is better (compulsory) to use copy for NSString attributes...

  • But what if I want to have a @property to an int or an enum ?

  • Shall I choose the weak attribute if my @property points to a singleton ?

You see : so many questions for theses attributes !

I thought it would be nice to have a short and clear explanation of these attributes as some members here do :)

Colas
  • 3,473
  • 4
  • 29
  • 68

1 Answers1

2

A few notes in no particular order

  • weak has the additional features of being nil-ed out when the referred-to object is deallocated, so you are never left with a dangling pointer to garbage
  • It is not compulsory to use copy semantics with an NSString property, but it is highly recommended. While NSString is immutable, your property might be set to a mutable string subclass, so if you don't want it changing out from under you, you should use copy
  • The rule of thumb for scalar property types is pretty simple: they are not reference counted, so neither strong nor weak applies. But they can be readonly or readwrite, depending on what you need.
PHD
  • 586
  • 1
  • 4
  • 11
  • So : for scalar properties, I can (should) put no property. I guess it is equivalent to `readwrite`. Thanks for your answer, it is nice points (I didn't know them, esp. point 1 and 2) !! – Colas May 02 '13 at 18:22
  • @Colas: They should still be properties, but you should not choose any ownership behavior (strong/weak/copy), since there is no ownership to be had. `readwrite` is a different issue, which is whether the property can be changed or not, and is a valid choice to make for all properties. – Peter Hosey May 03 '13 at 03:28
  • I would add that `copy` should be used for any and all copyable objects, not just strings. – Peter Hosey May 03 '13 at 03:33
  • @PeterHosey : Sorry, I meant "for scalar properties, I can put no attribute". I guess `@property int myInt` is equivalent to `@property (readwrite) int myInt`. Thanks ! – Colas May 03 '13 at 03:41
  • 1
    @Colas: That's true, but IMHO stating it explicitly makes things more readable, especially if others are using your codebase and might be surprised by the read/write semantics. – PHD May 03 '13 at 16:57