Properties in Objective-C (iOS)

Properties in Objective-C are used to store data in instances of classes. They define memory management, type, and access attributes of the values they store such as strong , weak , assign , readonly , readwrite , etc.





  1. atomic // Default
  2. nonatomic
  3. strong = retain // Default
  4. weak = unsafe_unretained
  5. retain
  6. assign // Default
  7. unsafe_unretained
  8. copy
  9. readonly
  10. readwrite // Default
In the article Variable property attributes or modifiers in iOS you can find all the above-mentioned attributes, and that will definitely help you.
  1. atomic
    • atomic means only one thread access the variable (static type).
    • atomic is thread safe.
    • But it is slow in performance
    • atomic is the default behavior
    • Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value.
    • It is not actually a keyword.
    Example:
        @property (retain) NSString *name;
    
        @synthesize name;
  2. nonatomic
    • nonatomic means multiple thread access the variable (dynamic type).
    • nonatomic is thread-unsafe.
    • But it is fast in performance
    • nonatomic is NOT default behavior. We need to add the nonatomic keyword in the property attribute.
    • It may result in unexpected behavior, when two different process (threads) access the same variable at the same time.
    Example:
        @property (nonatomic, retain) NSString *name;
    
        @synthesize name;
  3. assign is the default. In the setter that is created by @synthesize, the value will simply be assigned to the attribute. My understanding is that "assign" should be used for non-pointer attributes.
  4. retain  is needed when the attribute is a pointer to an object. The setter generated by @synthesize will retain (aka add a retain count) the object. You will need to release the object when you are finished with it.
  5. copy is needed when the object is mutable. Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.
  6. readwrite vs readonly - "readwrite" is the default. When you @synthesize, both a getter and a setter will be created for you. If you use "readonly", no setter will be created. Use it for a value you don't want to ever change after the instantiation of the object.

Post a Comment

0 Comments