Encapsulation is one of the basic building block in Object Oriented paradigm. Encapsulation in Java is achieve by restricting user to directly access the fields of Object and in order to access those fields, setters and getters are written. Objective C is also an object oriented programming language and also provides encapsulation by providing setters and getters to access the object data. Here is the sample class which contains two fields. One is an object and second one is of basic data type.
@interface TestClass : NSObject
{
NSString *name;
int id;
}
- (void) setName : (NSString *) newName;
- (NSString *) name;
- (void) setId : (int) newId;
- (int) id;
"setName" and "name" is setter and getter of "name" field. Similarly "setId" and "id" id setter and getter of "id" field.
Here is the implementation part of class
@implementation TestClass
{
- (void) setName : (NSString *) newName
{
[newName retain];
[name release];
name = newName;
}
- (NSString *) name
{
return name;
}
- (void) setId : (int) newId
{
id = newId;
}
- (int) id
{
return id;
}
}
setName needs your special intention for memory management point of view. First you send message "retain" to parameter, then you release old field by sending message "release" to name pointer. Then you assign new value to name pointer. These three steps are critical because if you change the order like you release old one and then retain new parameter, if both are same, then by sending release message will free the memory and new parameter will also be freed because that was same as old one. By sending retain message to parameter, you actually gain ownership of it and its reference count increases. Since you have also ownership of old one, so you will have to release it otherwise you will lose reference and there will be memory leak. Now as a java developer i can think that if "name" field is null, then sending release message may give something like NullPointerException but in Objective C, sending a message to null is safe and it will not throw any error and will keep executing next line.
Now last thing which is missing is that how to release fields which are retained before releasing object memroy, so for that you will have to overwrite a special method of NSObject "dealloc". This method is called when you send release message to an object and its reference count is 0. In this method you will have to release all those objects which you have retained. Sample implementation for above class is given below:
- (void) dealloc
{
[name release];
[super dealloc];
}