Showing posts with label Objective-C. Show all posts
Showing posts with label Objective-C. Show all posts

Saturday, June 23, 2012

Dot operator in Objective C

In Objective-C, dot operator can be used to access the member function of a class. The syntax makes you feel that you are directly accessing the instance variable of a class, but you are not.

You can can use dot operator to.
  1. to access the member function with zero argument and 
  2. to access the member function with one argument with no return value. Provided the name of the function starts with word 'set' and the character just after 'set' is an uppercase ascii or an underscore.
Lets see this with example

File: TestVariableAccess.m
#import "TestVariableAccess.h"

@implementation TestVariableAccess

-(int)function{
    NSLog(@"function_ret");
    return 100;
};


-(int)setFunctionWithArg:(int)arg{
    NSLog(@"function_ret withArg %d", arg);
    return 101;
};


@end


These functions can be called with the dot operator as follows.

The below code will call the method named function and the return value is assigned to the variable a.

TestVariableAccess *obj = [[TestVariableAccess alloc]init];
int a = obj.function;

The below code will call the method named setFunctionWithArg. Note that the compiler adds the word 'set' to the method name and makes the first character in the method name to uppercase before calling the method.

TestVariableAccess *obj = [[TestVariableAccess alloc]init];
obj.functionWithArg = 10;


Setters and getters

Though the dot operators can be used to call any method abiding to the above mentioned rule, it is meant to be used for setters and getters.
Consider the below declared variable value

TestVariableAccess.h
@interface TestVariableAccess : NSObject{
    int value;
}

-(int)value;
-(void)setValue:(int)v;

@end

TestVariableAccess.m
#import "TestVariableAccess.h"

@implementation TestVariableAccess

-(int)value{
    return value;
};


-(void)setValue:(int)v{
    value = v;
};


@end

Here the getter is value and the setter is setValue. In Objective-C the name of the getter is same as that on the name of the variable and the name of the setter is variable name prefixed with 'set' word with the first character in the variable (if it is not underscore) is made to upper case.

With the dot operator, the getter is called by
TestVariableAccess *aa = [[TestVariableAccess alloc]init];  
int v = aa.value;

and the setter is called by
TestVariableAccess *aa = [[TestVariableAccess alloc]init];  
aa.value = 12;

This way we can access the instance variable with dot operator through setters and getters. Though the code seems like we are accessing the instance variable directly, we are not. Instead we are accessing the variable through setters and getters.

If there is not setters and getters defined, the compiler will throw error. 

Accessing public variable directly

You can declare a public instance variable in Objective-C class as shown below.

@interface TestVariableAccess : NSObject{
@public
    int pubValue;
}
@end

Public variables can be accessed without declaring setters and getters. Since the dot operator is reserved for setters and getters, the Objective C  uses -> operator to access the public variable.

TestVariableAccess *aa = [[TestVariableAccess alloc]init]; 
        
// Setting value
aa->pubValue = 12;
        
// Getting value
int v = aa->pubValue;
        

Thursday, June 21, 2012

interface keyword in Java and ObjectiveC

There is an interface keyword in both ObjectiveC and Java (in Objective-C it is @interface). Are they used for the same purposes ?

Answer: No.

We will see this in detail.

interface keyword in Objective-C


In C, a function (that is accessed by a different file) is usually written in two files. In .c and .h files. We write the function prototype in .h file and the function body in the .c file. 
The .c files, of course with the help of .h files, is compiled to form the libraries (.a, .o, .so etc. ) and executable where as the .h files are used by the code that uses these libraries. 
The .h files thus act as a document for anybody who is using this library. By checking the .h file one can understand what APIs this library offers. The .h files also help the compiler to understand the symbols (function name, variable names etc ) of the external libraries that you are using in the code. 

Objective-C also adopts the same philosophy. 

A class in Objective-C is , usually, is a combination of a .m and a .h file. 

Here, the .m file is used to write the function body in a class, where as the .h file is used to write the function prototype (or interface), variable declaration, mention class inheritance etc.  

In .h file the function declaration are mentioned between the keywords @interface and @end and in .m file the function bodies are mentioned between the keywords @implementation and @end. 

Example


.h file

//SampleClass inherits from NSObject
@interface SampleClass : NSObject

// Variables are declered between these curly braces. 
{
    int value1;
}

// Setter for value1
-(void)setValue1:(int)v;


//Getter for value1. Note that there is no 'get' word in the getter. By convention, in 
// Objective-C the getter function name is same as the variable name. 
-(int)value1;

@end

.m file

#import "SampleClass.h"

//Implemetation of the prototype defined in SampleClass.h
@implementation SampleClass


//Implementation of setter
-(void)setValue1:(int)v{
    value1 = v;
}


//Implementation of getter
-(int)value1{
    return value1;
}

@end


interface keyword in Java


interface in Java is used to enable dynamic binding and thereby polymorphism. interface is just an agreement that defines some function prototype. A class using this interface can take any object who is adhering to this agreement. Any class can adhere to the agreement by just implementing the function prototype of the interface.

Example

Interface (Agreement)
// This interface is a agreement. Any class can adhere to this agreement by 
//implementing this interface. 

public interface SampleInterface{
// You can have more function in this interface. 
    void printValue();

}


Implementation (A Class adhering to the above agreement)
public class SampleImplementationOne implements SampleInterface{
    
    void printValue(){
        System.out.println("This is SampleImplementationOne");
    }
}


User - This class uses the interface SampleInterface. Note:- Nowhere in the class there will be mention of any of the implementation of this interface (such as  SampleImplementationOne). There is only reference of SampleInterface. The function printLogValue can take any class that implements the interface SampleInterface.
public class UserClass{

    void printLogValue(SampleInterface sample){
        sample.printValue();
    }
}
If we pass SampleImplementationOne to the function printLogValue, it will print "This is SampleImplemetationOne".
public static void main(String[] args){

    UserClass uc = new UserClass();
    uc.printLogValue(new SampleImplementationOne());
    return;

}
The class UserClass decides which implementation of SampleInterface is passed at the run time. This is a powerful feature and you can decide which implementation class to use at the run time.

Consider the following case.

Suppose you are implementing a network communication module. It helps if you define an interface (NetworkAdapter) that will declare prototypes for send and receive functions. This way you can choose your implementation of NetworkAdapter for Bluetooth, Wifi or any other interface at runtime.

The interface also help in development. Suppose the code of both Bluetooth or WiFi is not ready when you start development of your communication module. You can write your own DummyAdapter (implementing NetworkAdapter) for testing. When the Bluetooth or WiFi is ready, you can change the DummyAdapter to the corresponding implementation.

Dynamic binding in Objective-C

Now you see that the Java make use of the powerful dynamic binding with the use of interface keyword. How does Objective-C make use of dynamic binding? With the use of @protocol keyword. The detail of which is out of the scope of this article. See here for more details on protocol.


Thursday, June 7, 2012

Method name in objective C


One thing that keeps you a bit puzzled at the start of learning objective C is its function(method) declaration inside a class. Most of the developers who migrated from other languages like C , java, python, javascript etc may never have encountered with such use of function names.

Lets see an example

- (float) divideNumerator:(int)numerator withDenominator:(int)denominator{
    /* Calculate and return result */
}

'-' tells that it is a instance method. To declare a class method, we will use '+' sign

(float) is the return type.

Now if you see the method name and argument, you will see a repetition of patterns like this. The pattern is repeated for all the arguments,

key:(return_type)value

For example:

divideNumerator:(int)numerator and
withDenominator:(int)denominator

Here the keys are divideNumerator and  withDenominator whereas the values are numerator and denominator.

The method name is nothing but the combination of keys ending with colon, that is in this case, the method name is

divideNumerator:withDenominator:

In method with no argument, there is only one key with no values,  for example

-(float)getResult{
    /*Return result*/
}

In this case, the method name is

getResult:

Passing messages to a method. 

In Objective C, an instance method called is termed as Passing message to the object. For example

float value = [obj divideNumerator:20 withDenominator:10];

Here the method divideNumerator:withDenominator: is called with arguments 20 and 10. The argument passed also have a key:value pattern, where keys are the same as mentioned in the method declaration.