By A Beginner

Every Expert Was Once A Beginner

@property in Objective – C — June 28, 2015

@property in Objective – C

The keyword ‘@property’ in Objective-C can can be associated to a data member, to tell how the assessors can be automatically generated by the compiler. Which help us writing less code and saving the development time.  When the data member (instance variable) as a property ,it becomes available to the other classes to access or change its value using the accessors methods.

Declaring property

The properties can be declared in the @interface or the @implementation of the class with the appropriate attributes, but best practice is to declare them in the @interface of the class if it has to be accessed or changed by the other class. when declaring the property we can specify how the instance variables are exposed to other classes.

When you declare a property, you are telling other objects that getter and setter methods for accessing and changing one of the class’s instance variables exist.

Syntax for declaring the property in Objective-C:

@interface SomeClass : NSObject

@propert type name;
       //or
@property (attributes) type name;

@end

Property Attributes

Property attributes describe to other objects(and to the compiler) how the property behaves. The possible access specifiers are :

  • strong –   This property is a strong (owning) reference to an object. Using strong and weak properties controls whether the object referred to by the property stays in memory or not.
  • weak – This property is a weak (nonowning) reference to an object. When the object referred to by this property is deallocated, this property is automatically set to nil.
  • copy – This property’s setter copies any object passed to it, creating a duplicate object.
  • assign – This property’s setter method simply assigns the property’s variable to whatever is passed in, and performs no memory management.
  • readonly – This property does not generate a setter method, rendering the property read-only by other classes. (Your class’s implementation code can still modify the property’s variable, however.)
  • readwrite – This property generates both getter and setter methods. (This attribute is set by default—you need to explicitly use it only when overriding a superclass’s property.)
  • nonatomic – This property’s setter and getter do not attempt to get a lock before making changes to the variable, rendering it thread-safe.
  • getter=…, setter=… – Used when you want to change the default name of the accessors.                                               Eg:- @property (copy,getter=myGetter,setter=mySetter) NSObject *myObject;

 In a garbage-collected environment, retain is not different from assign. But in that case, the attributes __weak and __strong can be added.

Keywords @synthesize and @dynamic

@synthesize : This means that, unless developer already did it, the compiler should generate the accessors by it self, confirming to the constraints that were used in the property declaration. (With ARC all the properties are auto-synthesized and no need to explicitly synthesize the property explicitly in the @implementation)

@implementation A
@synthesize myProperty =_myProperty; //bind to "_myProperty" rather than "myProperty"
//(which does not even exist here)
@end

@dynamic : This means , it is up to the developer to provide the expected implementations of the accessor methods (a mere setter if read-only was specified when declaring the property; getter and setter otherwise).

If you do choose to mark a property as @dynamic, you need to implement the getter and setter methods yourself as shown below:

@implementation MyClass
@dynamic myProperty;
- (int) myProperty {
// this is the getter method for this property
      return 123;
}

- (void) setMyProperty:(int)newValue {
// this is the setter method for this property
}
@end

To understand more about @property refer:

  1. Encapsulating data

KVO In Objective – C — June 17, 2015

KVO In Objective – C

What is KVO ?(Key Value Observing)

KVO – Key Value Observing ,is the feature provided by COCOA which allows an object to register itself to be notified when another object changes the value of one of its properties. Here the controller would ask the model object for notification when the data changes , when the controller receives the notification from the model, the view is updated.

KVO simplify the process of registering for notifications ,and notifying any changes any objects that need to be told of the changes. Any property of an object can be observed , as long as that property’s name is key value coding compliant.

How to Register an Object For Change Notifications?

An object can register itself to be notified of the changes of its properties by the other object, by  telling the object to be observed the following : the object that should be notified when the property changes, the name of the property that should be observed, and the information the observer should be told about when the when change happens. Optionally , we can also include the pointer or object reference that should be passed to the method that is run when the change in the value of the property happens.

Eg: –

[aPerson addObserver:self
          forKeyPAth:@"personName"
             options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld)
             context:nil];

In the above snippet we see that the object we add an observer for the ‘personName’ property of the object ‘aPerson’ to be observed by the ‘self’ object , which is notified with the old and new values of the property ‘personName’ of the ‘aPerson’ object.

Once the object has registered itself as the observer of another object, this object recieves the message ‘observeValueForKeyPath:ofObject:change:context:‘. This message has the following parameters:

  • The key path of the property that changed -[personName]
  • The object whose property changed -[aPerson]
  • An NSDictionary that contains information about the change -[change dictionary]
  • The context variable that was passed in when addObserver:forKeyPath:options:context: was called -[nil]

The change dictionary contains the different information dependin on what options wer passed in when the observer was added.

Eg:-

  • NSKeyValueObservingOptionNew :  then the dictionary contains the NSKeyValueChangeNewKey key, whose object is the value that the property has been set to.
  •  NSKeyValueObservingOptionOld : then the dictionary contains the  NSKeyValueChangeOldKey key, which can be used to get the previous value of the property.

Eg:-

The example for how an object can handle the aPerson object changing its personName property :

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
       if ([keyPath isEqualToString:@"productName"]) {
           NSString* newPersonName = [change objectForKey:NSKeyValueChangeNewKey];
        // tell the appropriate view to update, based on the newPersonName variable.        }
}

How to Notify the Observers of the Changes?

Whenever implementing the key-value observation, the objects need to notify their observers when their properties change.

If the properties are declared using the ‘@property’ syntax and have compiler synthesize the accessor methods, then the object is automatically notify any registered observers when the setter methods are called.

If Objective-C properties syntax is not used for declaring the properties, or if you override the setter methods for a property , you need to manually notify the system of the changes that are being made.To do this, you call the willChangeValueForKey: and didChangeValueForKey: methods on the self object. This allows the key-value observing system to keep track of the previous and new values of a property.

Eg: – How to override the setter method for the personName property of aPerson object.

- (void) setPersonName:(NSString*)newPersonName {
          [self willChangeValueForKey:@"personName"];
          productName = newProductName;
          [self didChangeValueForKey:@"productName"];
}

To know more on KVO refer:

  1. Introduction to Key-Value Observing Programming Guide
  2. Understanding Key-Value Observing and Coding