domingo, 11 de diciembre de 2011

Basic language syntax III


Properties help us to define a piece of information, either a variable or object, and that it is visible to all classes that are going to consume it.
To create a property on the interface we must write the following

  1. //Property example
  2. @property(nonatomic,retain) NSString *example;

The parentheses "()" will specify the attributes of our property, for example, I decided to use nonatomic and retain.

Nonatomic means that if the setter or getter is being accessed from multiple threads, can not be interrupted, also nonatomic properties are much faster to access.

Making alloc and init makes retain count increases by 1.

On implementation side we call the @synthesize, to tell the compiler to generate the methods getter / setter that are necessary for the attributes that we have specified in the property.
For example:

  1. //@Synthesize generates our getter/setter functions
  2. @synthesize example;

To use it we call it this way:

  1. //Use self. to call our properties
  2. self.example = @"This is a test";

If we want to have a class variable and maintain the state both inside the class and when accessed from outside, we do as follows:


  1. @interface Test : NSObject
  2. {
  3.     NSString *_example;
  4. }
  5. @property(nonatomic,retain) NSString *example;


  1. @implementation Test
  2. @synthesize example = _example;

When we use it

  1. self.example = @"Test";
  2. //Or...
  3. _example = @"Test";

2 comentarios:

  1. Este comentario ha sido eliminado por el autor.

  2. Hi muayguy,
    I agree with you, but i was just explaining how properties work, not combined with ivars, i'll do that later.