Pankaj Gupta
Pankaj Gupta

Reputation: 81

Objective C : @property declaration and instance variable declaration

Though the question is basic, but I found it very crucial to understand to proceed with IOS programming. Sometimes we used to declare only instance variable and we don't set any associated property to it. Some where we just declare the properties and use synthesize to get or set the values. Sometimes I feel necessary to declare both in code, when compilation gives me warnings! What's the fundamental behind the manipulation of properties in Objective C. I know the basic requirement to create getter and setter for any instance variable, but when? I have seen it many times we don't use property at all, and after that too we easily set and get variable's value. Also, different types of property like atomic, non atomic, strong, retain are very unclear to me. XCODE up-gradation to 4.2 has shaken my concepts about memory management. Can somebody please clear the cloud over my mind?

Upvotes: 4

Views: 1915

Answers (2)

user187676
user187676

Reputation:

Properties are always the preferred way over direct ivar access, mostly of following reasons:

  • You can override a getter or setter in a subclass
  • You can define the "assigning behavior" (namely copy, assign, retain/strong, weak)
  • You can synchronize ivar access

Keywords:

  • copy: The object is copied to the ivar when set
  • assign: The object's pointer is assigned to the ivar when set
  • retain/strong: The object is retained on set
  • weak: In ARC this is like assign, but will be set to nil automatically when the instance is deallocated, also used in a garbage collected environment.
  • nonatomic: The accessor is not @synchronized (threadsafe), and therefore faster
  • atomic: The accessor is @synchronized (threadsafe), and therefore slower

Generally you should always synthesize an ivar. If you need faster access for performance reasons you can always access the synthesized ivar directly too.

Upvotes: 9

Justin
Justin

Reputation: 2999

While typing I saw that 'Erik Aigner' was faster with a good answer.

For een example on properties, synthesize and custom setter see my answer on stack: Objective-C convention to prevent "local declaration hides instance variable" warning

For an stater tutorial on ARC see the explenation on Ray wenderlich his website:

Beginning ARC in iOS 5 part 1 and

Beginning ARC in iOS 5 part 2

Upvotes: 2

Related Questions