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

Sunday, March 3, 2013

Delegate Design Pattern : Objective C vs Java

One of the most used design patterns in iOS is Delegate Design Pattern. The main usage on this design pattern is to delegate some functionality from called component to caller controller. On image below is shown simple diagram of this pattern where from main controller we call custom component with action to show data from concrete page loaded from the model. The custom component loads data and then displays. In case when no data is loaded for requested page the custom component throws notification thru implemented method in main controller from the custom component protocol. We can look on protocols in Objective C as in interfaces  in Java so the method which is defined in the protocol should be implemented in the the controller that expect some event delegated from the custom component, and also set instance on the caller controller to the custom component where the custom component will use method declaration to send some data to the caller controller or will try to execute the method.

       Delegate Design Pattern

To be much easier to understand, we’ll make comparison on implementation on delegate design pattern in iOS and in Java and we’ll see how can we create custom components in both platforms and use that components to return data to controllers where they are called.

Objective C version

ViewController.h

#import
#import "ServiceConsumer.h"

@interface ViewController : UIViewController

@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
ServiceConsumer *consumer = [[ServiceConsumer alloc] init];
consumer.delegate = self;
[consumer returnNumberToDelegate];
}

#pragma mark -
#pragma mark - ServiceConsumerDelegate methods

- (void)executeWithResult:(NSInteger)testValue {
NSLog(@"Returned value from delegate is %d", testValue);
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

In header file we import delegate module but also we conform with the delegate of the module. In implementation we make instance from the service consumer but also we set the delegate to self which mean we need to implement the methods defined in the protocol.

 ServiceConsumer.h

#import

@protocol ServiceConsumerDelegate

- (void)executeWithResult:(NSInteger)testValue;

@end

@interface ServiceConsumer : NSObject

@property (nonatomic, strong) iddelegate;

- (void)returnNumberToDelegate;

@end

ServiceConsumer.m

#import "ServiceConsumer.h"

@implementation ServiceConsumer

@synthesize delegate;

- (void)returnNumberToDelegate {
[self.delegate executeWithResult:32];

}


@end

In ServiceConsumer header we can see the protocol definition but also the most important line, property definition as id – generic object that have to confirm to the protocol defined in here. In implementation we can see the method that call method executeWithResult which is defined in the protocol but it call it from the delegate property which mean that the class that will have implemented the method defined in the protocol and also confirms with the delegate, if that class call the method returnNumberToDelegate from the ServiceConsumer that class will receive the response in implemented method executeWithResult. We can see that the functionality is delegated thru line [self.delegate executeWithResult:32];

Java version

With creation on instance of the ServiceConsumer we initialize engine with the instance that implements IServiceConsumer interface. That is done in constructor here. In this class we also have one method returnConsumerData that same as in Objective C version, if is called from the class that implements that interface and have implementation for method printMessage defined in the interface, this method will call that method thru the instance set to interface in the constructor.

ServiceConsumer.java

public class ServiceConsumer {

private IServiceConsumer consumer = null;

private static final String MESSAGE_0 = "MACHINE IS RUNNING";
public ServiceConsumer(IServiceConsumer consumer) {
super();
this.consumer = consumer;
}
public void returnConsumerData() {
this.consumer.printMessage(MESSAGE_0);
}
}



In Java version instead of protocol in Objective C we need to have interface with defined method.

IServiceConsumer.java

public interface IServiceConsumer {
public String returnConsumerData(String data);
public void printMessage(String messgeData);
}

The class that calls the engine makes instance from the ServiceConsumer class with setting the Machine.this to the constructor of the ServiceConsumer class because it already implements the interface. Also because it implements the interface it should also implement the methods defined in the interface in this case returnConsumerData. Method loadConsumerData is used to call returnConsumerData method implemented in the ServiceConsumer, which after calling return data thru method printMessage.

Machine.java


public class Machine implements IServiceConsumer {
private ServiceConsumer consumer = null;
public Machine() {
this.consumer = new ServiceConsumer(Machine.this);
}
public void loadConsumerData() {
this.consumer.returnConsumerData();
}


@Override
public String returnConsumerData(String data) {
// TODO Auto-generated method stub
return data;
}

@Override
public void printMessage(String messgeData) {
// TODO Auto-generated method stub
System.out.println(messgeData);
}

}


Monday, December 19, 2011

Objective C from a Java Developer perspective Part I

We are witness how mobile development is spread across the IT industry with rising of Apple’s iPhone and Google’s Android. There are many other mobile platforms like J2ME, BlackBerry, Symbian, Windows Mobile 7 that are trying to take a pace from the mobile cake but as we see currently Android and iOS are leading mobile platforms.

In this document I’ll try to make comparison between Java and Objective C as main languages for developing on those mobile platforms.

Objective C is main programming language for developing on Mac OSx. Its developed as C/C++ alternative based on SmallTalk which covers whole OOP paradigm. As language, is a little bit different than any other C like language but compared for example with Java is much more simpler. In the following text I’ll try to make simple comparison between Java and Objective C and to explain the differences.

Variables and Methods

In the table below Objective C variable primitive types and class types are displayed with same Java alternative.

Objective C
Java
id
NSObject
NSInteger
NSString
BOOL
NSFloat
NSNumber
NSData/NSMutableData
NSArray
NSMutableArray
NSMutableDictionary
NSSet
NSDate
NSCalendar
Int
long
long long
bool
float
double
char
-
short
Class
Object
Integer
String
Boolean
Float
-
Byte
[]
List
Map
Set
Date
Calendar
Int
long
-
boolean
float
double
char
byte
short

As we can see, primitive types, class types and collections are very similar in both languages.For every type in Objective C we have almost the same type in Java.

Initialization on primitive types is same in both languages but on class types and on collections is a little bit different. In the next table we can see those differences.

Objective C
Java
int test = 0;
char name = ‘John Doe’;
NSInteger *number = [[NSInteger alloc] init];
NSString *stringType = [[NSString alloc] init];
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
NSNumber *genericNumber = [[NSNumber alloc] numberWithInt:1];
int test = 0;
char name = ‘j’;
Integer number = new Integer();
String stringType = new String();
List dataList = new LinkedList();
-

Testing for the class type is made like this:
isKindOfClass
instanceof

Setting/Getting the object from the Collections

Objective C
Java
NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObject:@”Test”];
[arr addObject:@”Test 2”];
NSString *testObj = [arr objectAtIndex:0];
id *testObj = (NSString *)[arr objectAtIndex:0];
1. List objList = new LinkedList();
2. ListobjList = new LinkedList();
objList.add(new String(“Test”));
objList.add(new String(“Test 2”));
1. String testObj = (String)objList.get(0);
2. String testObj = objList.get(0);

In Objective C collections can keep mixed type of objects, same in Java except that in Java we can use generics to set which type of objects we’ll keep in our list. Casting work same in both languages.

Static constants in Objective C are declared as #define macro directive, same for int and char where in Java with using special keywords static and final, for example:

Objective C
Java
#define NUMBER_OF_MONTHS 12
#define YEAR _ATTRIBUTE @”year”
public static final int NUMBER_OF_MONTHS = 12;
public static final String YEAR _ATTRIBUTE = “year”;

We can set static keyword to the property in Objective C but that not mean that work same as in Java, static keyword mean that the property is visible inside that class but if we want that property to be visible outside that class we should implement static accessors methods for each static property. In the table we’ll see also method definition in both languages and returning type.

Objective C
Java
@interface MyClass
{
NSString myVar;
}
+ (NSString *)myVar;
+ (void)setMyVar:(NSString *)newVa;
@end
@implementation MyClass
static NSString *myVar;
+ (NSString *)myVar { return myVar; }
+ (void)setMyVar:(NSString *)newVar { myVar = newVar; }
@end
[MyClass setMyVar:@”Test Value”];
NSLog(@”%@”,[MyClass myVar]);
public class MyClass {
public static String myVar;
public static String getMyVar(){ return this.myVar;}
public static void setMyVar(String myVar) {
this.myVar = myVar;
}
}
MyClass.myVar = “Test Var”;
System.out.println(MyClass.getMyVar());

Sign plus (“ + “) is used for making the method static instead of using sign minus (“ – “) for not static methods.

Methods work same in both languages, the difference is only in declaration of returning type and in passing arguments.

Objective C
Java
-(void)executeWithoutResult { }
-(void)executeByName: ( NSString *)name { }
-(void)executeByNameAndAge: (NSString *)name age: (int)age { }
-(NSString *)findUserById: (int)userId { }
+(int)findUserAges: (int)userId { }
public void executeWithoutResult() { }
public void executeByName(String name) { }
public void executeByNameAnd Age(String name, int age) { }
public String findUserById(int userId) { }
public int findUserAges (int userId) { }
Depending on sign plus (“ + “ ) or minus (“ – “ ) method will be static or not. After the sign we put the returning type in small brackets. Depending on returning type we can return primitive type, or Class type pointer. After the brackets method name is defined. After the method name we put colon for method parameters declaration. Before every parameter we put the parameter type. Parameters are separated with space. Parameters are declared as, parameter name colon parameter type in brackets and after that again parameter name. After last parameter we open curly bracket for methods body.
Calling the methods is also different in both languages. Objective C use message passing system for executing instance methods where in Java methods are called with dot between the object and method we want to call.
Classes and objects
Class implementation is different in both languages. In Objective C custom class must inherit from NSObject, where in Java everything inherits from Object. In Java simple classes are known as POJO or Plain Old Java Object. These classes may encapsulate properties with different data types also they may or may not contain methods used for getting and setting the properties. In the table below we can see implementation in both languages.
Objective C
Java
CustomObject.h
@interface CustomObject:NSObject{
@public
NSString *stringValue_;
@private
NSInteger *integerValue_;
}
@property(nonatomic, assign) NSString *stringValue;
@property(nonatomic, assign) NSInteger *integerValue;
@end
CustomObject.m
#import “CustomObject.h”
@implementation CustomObject
@synthesize stringValue = stringValue_;
@synthesize integerValue = integerValue_;
-(id)init{
self = [super init];
if(self){
//call init methods
}
return self;
}
-(void)dealloc{
stringValue = nil;
[integerValue release];
[super dealloc];
}
@end
CustomObject.java
public class CustomObject{
public String stringValue;
private Integer integerValue;
public CustomObject(String stringValue, Integer integerValue){
this.stringValue = stringValue;
this.integerValue = integerValue;
}
public String getStringValue(){
return this.stringValue;
}
public void setStringValue(String stringValue){
this.stringValue = stringValue;
}
public Integer getIntegerValue(Integer integerValue){
return this.integerValue;
}
public void setIntegerValue(){
this.integerValue = integerValue;
}
}

Initialization and setting/getting the values from the properties

CustomObject *obj = [[CustomObject alloc] init];
obj.stringValue = @”Test Value”;
[obj setStringValue:@”Test Value”];
NSLog(“%@”, obj.stringValue);
NSLog(“%@”, [obj getStringValue]);
[obj release];
CustomObject obj = new CustomObject();
obj.stringValue = “Test Value”;
obj.setStringValue(“Test Value”);
System.out.println(obj.stringValue);
System.out.println(obj.getStringValue());

As we see in the table implementation on classes in Objective C is a little bit bigger then in Java when we have small number of properties, but in case when we have bigger number of properties if we use getters/setters in Java, the code will be much more bigger then in Objective C. Why?

In Objective C classes are implemented in two different files, one for interface and the other one for implementation, in special cases for private access to some properties, beside the required interface, we can implement interface also at the beginning of the file where we our class is implemented. We can set access type to the properties by setting @public, @private, @protected above the block of properties where in Java special access keywords are put at the beginning of the each property definition. For restricting access to the methods, in Java we set one of three access keywords before the method declaration where in Objective C that is done with duplicate interface definition at the beginning of the class implementation and with private implementations:

@interface MyClass(Private){
-(void)someMethod;
}
@end
@implementation MyClass
-(void)someOtherMethod {}
@end
@implementation MyClass (Private)
-(void)someMethod {}
@end
public interface IMyClass{
private void someMethod();
}
public MyClass implements IMyClass{
private void someMethod() {}
}
Where in Java we can use interface or just put set the method as private. Classes in Objective C are always pubic where in Java we can also set access rights to the class or interface which will restrict access the that class or interface. Special keyword @synthesize will automatically create getters/setters for our properties, that’s not mean that we can’t implement getters/setters by our self, but this keyword is mostly used. In Java we can implement interface in separate file and then our class will implement that interface, we can implement the interface at the beginning of the file where our class is implemented ( but this is bad practice ), and also we can implement the class without using the interface as we saw in the example. In every class implementation in Objective C there are also two methods that should be implemented, init and dealloc. Init method is same as constructor in Java, but if we not implement this method, the init method will be called from the super class that we extends, same for dealloc. We can have many different init methods same as constructors and each of them can be used in different situations, but only one dealloc method in the class must be implemented. Dealloc method Is used for deallocating reserved memory for instance and class variables, local variables are deallocated at the end of each method.
Protocols and delegates

In the next part i'll make brief comparison between Objective C protocols and delegates and Java alternatives.

Thursday, November 24, 2011

iOS UI Runtime Builder based on XML Definition

The basic idea behind this toolkit is to separate UI implementation from the source code. This idea comes from the beautiful Java toolkit SWIXML which was implemented for allowing separation on UI from business logic in Swing based applications. This toolkit is also implemented in Android SDK core for same reason and is much more used then hard coded UI. The concept mutates to new programming paradigm which is also known as declarative programming where we specify UI and we regardless of how it will be created we just want initialized elements to manipulate with.

With using tool that allows us to make separation on UI from the business logic we will have cleaner code which is much better for reading and maintaining than putting everything into the class.

In iOS you can make UI with setting all properties into the code for every view that we use or by using Interface Builder which generate some messy XML structure that is understood only by the Interface Builder itself, but in this case because everything is auto generated we can’t change anything into this XML. Application that is implemented with using Interface Builder has also slower compile time than the application that has UI implementation into the view controllers. For that reason toolkit that separate UI from the code and keeps the UI definition as simple XML file instead of complicated XIB is welcome.

iOS Runtime UI Builder parse the XML UI definition with using the fastest XML DOM parser TBXML, creates object structure for every XML Tag with its attributes and keeps that objects in memory which is very fast because we don’t depend on complicated XIBs that are also slower to parse then simple XML file. After parsing and creating object structure, for every encapsulated view we automatically make initialization on each view with setting attributes which were defined in the XML Tags. The objects that encapsulate the views are stored into the fast data structure allowing us fast lookup for the concrete object and set initialized view to the reference into the code. With using this toolkit we make the code cleaner because every property is automatically set with changing complicated methods with only several written attributes into the XML Tags for every view that we create in main view. If we have complex views with many wrapped views inside them it’s not a problem, all that views will be automatically add into the parent view which gives us freedom to experiment with different UI concepts easily.

Check it on Google Code

https://code.google.com/p/ios-ui-runtime-builder/