6

I understand the reason i should use retain, but why should I ever use assign? (besides to avoid retain cycles)

[EDIT] So if i understand Chuck's answer on https://stackoverflow.com/questions... correctly, when ever I use assign, the variable would lose scope once it gets out of scope of the method just like it does in regular C-type language behavior?

Community
  • 1
  • 1

4 Answers4

12

You should assign things that aren't objects. Any C type (such as int, float, char, double, struct, and enum) should be assigned.

DHamrick
  • 7,938
  • 9
  • 43
  • 58
2

Few examples I can think of:

  1. It is not an object. Such as BOOL, int
  2. Most of the times delegate properties are assigned (to prevent cycles)
mbh
  • 3,307
  • 2
  • 20
  • 23
1
  1. Anything that is not an object
  2. Delegates
  3. IBOutlets that are not top level (i.e. subviews since those are already retained by the view)
Oscar Gomez
  • 18,102
  • 12
  • 80
  • 113
1

Assuming that Chuck's answer from the linked question is correct, there's not really a "scope" in Objective-C. Sounds like you should just use assign for any primitives, like ints or BOOLs. Anything that you need to have ownership of, use retain (or other commands, as Chuck describes).

RaysonK
  • 553
  • 3
  • 8
  • 24
  • Ok. I understand that i need assign for primitives. Now what if i use assign for an object. Are you saying that that object is not guaranteed to be valid though-out its use if it wasn't previously retained? – stackoverflow Feb 04 '12 at 03:17
  • I can't say for sure because this is inferring from what that other user said, but near as I can tell, you're leaving it to the program to decide when the variable in question is done being used. Somebody correct me if I'm wrong, but I think `assign` just means you're going to change the value of the variable. – RaysonK Feb 04 '12 at 05:37