@property Attributes

Objective-C has a nice way of auto-generating getters and setters with the use of @proerty in the @interface and @synthesize in the @implementation. Just by adding two lines of code, the complier knows what to provide for these synthesized variables making some of the more routine tasks of programming a bit more maintainable. There are several attributes or properties that are used to help the compiler know how to handle the variables.


There are a number of attributes in parentheses that follow the @property:

Atomic versus Nonatomic

  • *atomic – Enforces thread safety. If getters and setters are performed in two different threads, ensure the variable completes setting before getting.
  • nonatomic – Faster, but doesn’t enforce thread safety.

You may be thinking, “hey I want to be thread safe.” However, nonatomic is almost always used. Most variables are simple assignments and the gain in speed is much better than having the compiler generating all of the memory locks.

Strong versus Weak

  • *strong or retain – Increment the reference counter for an object to ensure that it stays in memory.
  • weak or unsafe_unretained – Allow objects to be deallocated from memory if no other object is referencing it.

Objective-C used to require programmers to retain and release any variables that objects needed. This is no longer the case with the most recent iOS releases and the advent of automatic reference counting (ARC). This has offloaded much of the lower-level memory management to the compiler to figure out how to manage objects within memory. Strong and Weak are available in the @property attribute list to help advise how to perform this feature.

Assign versus Copy

  • *assign – Values are simply assigned in the getter and setter. Use for non-pointers.
  • copy – Make a copy of the variable. Use for objects that need to be reallocated when values change like NSStrings.

Readwrite versus Readonly

  • *readwrite – Both getter and setters are generated.
  • readonly – Only Getter generated. Use for variables that should not change after instantiation.

*Indicates Default

The methods generated or ‘synthesized’ will look like:

If desired, these methods can be overridden effectively giving control over them in the code. There is a way to rename one or both getters or setters with this variation:

Examples

It is generally considered good practice to rename the variable in the synthesize statement with a underscore. This helps differentiate the variable name and the local instantiation with the object itself. In the object, simply use _variableName.

Comments are closed.

Search

Websites

  • slide
  • slide
  • slide
  • slide