Archive for the ‘java versus Objective-C’ Category

06 – Attributes

March 19, 2011

The way how variables are defined in Objective-C is very different to Java. Since Objective-C is dealing with pointers (see (NSString **) value) and developers have to be aware of memory management, the definition of variables is much more complicated and powerful than in Java.

1 – Java attributes

In this blog post I decided to start with the very basics based on Java.

We are deciding between two different kind of variables:

  • instance variables
  • class variables

1.1 – Instance variables

An instance variable is an attribute from a classes instance and exists for each instance. It will be initialized during the creation of the class instance. Instance variables can only be accessed by class instances and not by classes.

Instance variables are accessed like this:

SomeObject object = new SomeObject();
String value = object.value;

 

 

1.2 – Class variables

A class variable is an attribute of a class and exists exactly once by class and classloader. It will be initialized at class loading time and can be accessed by classes and class instances. All instances of a class will share this unique state of the variable. If you change the variable, it becomes changed for all instances of this class.

Class variables are accessed like this:

String value = SomeObject.value;

 

1.3 – Visibility Modifier

Java decides 4 different visibilities:

  • public – visible for all objects
  • protected – visible for all subclasses. Also visbile for classes in the same package
  • private – only visible inside the class
  • default – only visible for classes in the same package

1.4 – Final Modifier

The final modifier defines, that a variable has to be initialized once during the class loading or instance creation, but must never change.

1.4.1 – Final instance variable

 

Final instance variables are used for different behaviours. Eg to ease the handling of concurreny or to protect the state of a class.

1.4.2 – Final static variable

 

Final class variables are often used for constant definitions. “static final String” are very common to define constants.

 

2 – Objective-C attributes

In the second part of this post i am going to define the attributes defined above using Objective-C.

We are going to start with instance variables.

2.1 – Instance variables

Variables are defined in the .h interface file.

If you do not define something special, the attribute has visibility “protected”. You can use it in the .m implementation file and deal with it. Also subclasses of MyClass can access the attribute.

This image shows the attribute access in a subclass of MyClass.

See also: iphonedevelopertips.com, omnigroup.com

2.2 – Class variables

Differing to Java, Objective-C does not allow to use public / protected class variables. If variables are defined as static, they are allways private.

static NSString *anAttribute;

This variable can only be used inside of the class which defines this variable.

Another very confusing behaviour of static attributes is the fact, that they can be defined inside a method and will retain their value during subsequent calls. For instance the singleton pattern uses this very havily.

See stackoverflow.com for a similar example and a detailed description.

 

2.3 – Visibility Modifier

If the attribtue should be accessible from other classes, you have to use visibility modifiers.

Please not, that static attributes are always private.

For explanation i changed MyClass and added 3 attribtues with 3 different visibilities.

 

No i am trying to access them from

  • MyClass.m – should work for all 3 attributes
  • MySubClass.m – should work for protected and public
  • OtherClass.m – should work for public
MyClass.m

Everything is fine. No problems reported.

 

MySubClass.m

 

Private attributes can not be accessed by subclasses.

 

OtherClass.m

Since OtherClass is not a subclass of MyClass, only public attributes can be accessed. For sure, directly accessing public attributes from classes outside the typehierarchy is not good pratice! But for demonstration it is really well.

 

2.4 – Final modifier

As you could see, the visibility modifier has a very close semantic to java. But what is about the final modifier?

Actually, Objective-C does not provide a final modifier, but the keyword const (means constant).

But Const offers a much more complex semantic as final does. It allows pointers and / or values of pointers to be defined as “constant”.
“Final” only defines a constant reference which can not be changed, since java does not divide between reference and its value.

Lets compare the different possibilities:

Java

private final Char someString;

The one and only way to define the char as final using java. Final means, that the value of the attribtue can only be assigned once. (During initilization)

Objective-C
It provides 3 different combinations of the const keyword.

// Pointer to constant char
const char* someString;


// Constant Pointer to char
char* const someString;


// Constant Pointer to constant char
const char* const someString;

We are going to use a few lines of code to get a feeling what i am talking about. The following image shows the three combinations of const mentioned above.

 

  • Example 1“const char* charPtr1″ means that the pointer charPtr1 is variable, but “the data the pointer is pointing to” is const. So only the “adress the pointer points to” can be changed. The “value the pointer is pointing to” is constant.

 

  • Example 2“char* const charPtr2″ means that the pointer charPtr2 is constant, but “the data the pointer is pointing to” is variable. So only the value the pointer is pointing to” can be changed. The “adress of the pointer” is constant.

 

  • Example 3“const char* const charPtr3″ means that the pointer charPtr3 is constant, and “value the pointer is pointing to” is constant. Nor the “value or the adress” of the pointer can be changed.

How to define final variables using Objective-C?

I found  a nice discussion about this issue: See iphonedevelopertips.com

Example 1 : final instance variable

Java
public final String MY_STRING = "MyString";

Objective-C:
.h-File:
extern const NSString* const MYSTRING;

.m-File
const NSString* const MYSTRING = @"myValue";

 

Example 2 : final static variable

Since static attributes are always private, we do not have to specify anything in the header file. It is enough to specify the attribute in the implementation file.

Java
public static final String MY_STRING = "MyString";

Objective-C:
.h-File:
==> Nothing to do. static attribute is always private!

.m-File
static const NSString* const MYSTRING = @"myValue";

05 – Protocol for Interface

March 10, 2011

Java Interface

Interfaces are used very havily inside of java applications. They allow the programmer to decouple different parts of the code and to make them independent.

Additionally they are used to define a contract which specifies methods which have to be implemented by subclasses. It is very comfortable to code against interfaces, rather than implementations.

Interface

Interface implementation

The following syntax is used to implement an interface into a class:

class MyClass implements SomeInterface

 

Objective-C Protocols

Objective-C provides a similar approach called Protocols. Protocols have a very close semantic as interfaces, but allow you to mark methods as @optional. Optional methods can be implemented by subclasses, but it is not required.

Protocols are defined by the @protocol directive.

@protocol SomeProtocol
    .... methods
@end

The SoundMachine protocol would look like this:

It’s really looks very close to the java declaration. Also the implementation class of this interface is very similar to java.

The .h file

and the .m file

 

ConformsToProtocol

If you would like to test whether a class implements a protocol you can use the conformsToProtocol message. It is similar to the instanceof check from java.

Objective-C: conformsToProtocol

Java: instanceof

 

@optional methods

In contrast to Java, Objective-C adds an additional semantic feature for protocols. Methods can be defined as optional. This means, that they do not have to be implemented by the class that implements the interface.

Java does not allow unimplemented interface methods. All the methods from an interface have to be declared in the classes type hierarchy.

The following image shows how optional methods can be implemented in Objetive-C:

If a class implements this protocol but does not add a method implementation for the optional methods, the compiler won’t mention this issue.

Therefore i have prepared an MyProtocolImpl.m class which implements MyProtocol. No methods have been implemented in the class before compiling it.

As you can see at the screenshot, the compiler only mentioned the missing required methods.

Calling an optional unimplemented method

If you are providing optional protocol methods, you have to ensure that messages are sent to these classes only if they implement the methods addressed by the message. Otherwise the call will result in an error.

The following image shows an implementation of MyProtocol. The anotherOptional-method is NOT implemented. A call to it would result in an error.

Therefore i have prepared a second class which will call the missing method by sending a message.

During the call of the anotherOptional-method call the Objective-c runtime sends the following error to the message console.

2011-03-10 12:56:02.923 MS4[21571:a0f] -[MyProtocolImpl anotherOptional]:
                        unrecognized selector sent to instance 0x1001611a0

To avoid such errors, the call schould be protected by the respondsToSelector message. This message will return FALSE, if the receiver of the message does not implement a method which responds to the message.

Since the receiver does not implement the method, it will not be called.

 

Additional informations

developer.apple.com

00 – Recommended Books

February 28, 2011

CocoaDesignPatterns

Beginning iPhone 3 development

Objective-C 2.0 (german)

04 – From SEL to IMP – or how to call a method

February 28, 2011

The way how methods are called in Objective-C is different to Java. If you are doing your first steps with Objective-C, it seems that sending messages to an object in Objective-C is exactly the same as calling methods in Java. A different syntactic way.

But sending messages and calling methods are two completely different things in Objective-C. A sent message will be converted into a method call by the message retrieving object.

In Java you just call the method.

MyObject.sayHello() calls the method directly

In Objective-C you do not directly call methods for normal. Instead you are sending messages to an object and let the message receiving object converts the message to a method call.

[MyObject sayHello] - The message is converted to a method call by MyObject

The message sent to an object is converted into an selector:

  • A message is a request to perform a specific method for an object. The message receiving object determines the method which should be performed based on the sent message by a selector.
  • The selector identifies the message sent to an object. A compiled selector identifies the method name of an object. The message receiving object uses the selector to select the method which should be called. Objective-C provides its own datatype for selectors.

SEL datatype

The SEL datatype is used to declare variables which store selectors.

SEL mySelector = @selector(doSomething);

“doSomething” is the message which will be sent to an object.

The defined selector can be used to send messages to an object too.

[myObject doSomething]
[myObject performSelector:mySelector]
[myObject performSelector:@selector(doSomething)]
[myObject performSelector:NSSelectorFromString(@"doSomething")];

These ways of sending messages will be treated equal by the receiving object.

It will select the method to be invoked based on the selector and calls it. Therefore C functions are used to determine the function pointer which identifies the method implementation. For detailed informations see developer.apple.com.

This instance method pointers (a function pointer to a function which implements an Objective-C method ) are stored in IMP variables.

IMP is defined by:

typedef id (*IMP)(id self,SEL _cmd,...);

To access the IMP, the message “methodForSelector” can be used.

IMP myImpDoSomething = [myObject methodForSelector:@selector(doSomething)];

The method adressed by the IMP can be called by dereferencing the IMP.

myImpDoSomething(myObject, @selector(doSomething));

So these calls are equal:

myImpDoSomething(myObject, @selector(doSomething));
[myObject doSomething]
[myObject performSelector:mySelector]
[myObject performSelector:@selector(doSomething)]
[myObject performSelector:NSSelectorFromString(@"doSomething")];

Detailed informations see developer.apple.com.

Messaging Errors

If a message is sent to an object which can not be handled, an error results.

You can use the respondsToSelector message to ensure that the receiver can handle the message.
if([myObject respondsToSelector:@selector(doSomething)]{
….
}

Message forwarding

If an object does not respsond to a message, it can foreward this message or use dynamic method resolution.

This issue is out of the scope of this blog. For detailed informations see dynamicMethodResolution and messageForwarding at developer.apple.com.

Patterns

Based on messages a couple of Objective-C patterns can be implemented.

Additional references

Selectors

Interacting with the Runtime

at developer.apple.com

03 – (NSString **) value

February 22, 2011

Java developer are familar with references. But sometimes they are not with pointers. But what is the difference. Isn’t a reference a pointer too?

Java does not make any difference between a reference and a pointer. If you keep a reference to an object, this reference represents the object which is the target of the reference. If you try to get a reference to this reference, you will fail using java, because java does not offer any semantics to access references on references.

Objective-C does. It allows you to access references on a reference and to deal with this reference. Additionally you can use arithmetics on this references. For instance you can add an integer value to a reference which will cause the reference to point to a different memory adress. By definition a pointer is a “variable which contains the adress in memory of another variable”.

Do make this circumstance more visual, have a look at the following image.

The variable charPtr is a variable containing a char-pointer (blue arrow) which points to a charValue.

Actually you can two different interesting things with the variable charPtr.

  • change the value the pointer is pointing to
  • assigning a different pointer
    // Helper variables
        // value of the char
        char val = 'someChar';
        // accessing the pointer to the char
        char *valPtr = &val;

    // change the value the pointer is pointing to. See the red X (char) at the image
        *charPtr1 = 'X';          // changing value of pointer
    // Assign a different pointer. See red arrow at the image
        charPtr1 = valPtr;        // changing adress of pointer

 

During the study of objective c you might have recognized the additional “*” for variable declarations.

  NSString *value

Variable declarations in java do not contain such a *

  String value

This * tells the compiler, that this variable is a reference / a pointer.

Lets try creating a pointer to a pointer.

  NSString **valuePtr

This variable represents a reference to a reference which’s target is the NSString value.

You can define this pointer also that way:

NSString** valuePtr

I am telling you this case, since it was a very helpful mnemonic for me. It can be very confusing if you are accessing values from pointers.

For me it was much more intuitiv setting the stars at the end of the type, rather then setting them to the beginning of the variable to define a new variable.

Using such **variables let you do really amazing things which are not possible using java.

For instance you can implement a get-method without a return value. Rather then returning a reference to the value, change the reference of the reference itself.

A try with java:

         ......
           String name = "NotFlorian";
           getName(name);
           // name is still NotFlorian!!!
         ......

          public void getName(String name){
                name = "Florian";
          }

This approach won’t change the value of the passed “String name”, because the method only changed the value of the local variable “name”. Since the local variable and the passed variable have different locations in memory, changing the local variable could not change the passed one.

A try with Objective-C:

         ......
           NSString *name = @"NotFlorian";
           [self getName:&name];
           // name is Florian!!!
         ......

         -(void) getName:(NSString **) valuePtr{
	      *valuePtr =  @"Florian";
         }

The Objective-C approach work really well! The big difference to the java approach is, that we did not pass a instance pointer (reference to a variable) but a reference to the instance pointer into the getName-method. The assignment changed the target of the reference pointer and so the *name variable in the calling code changed to the new value.

&name adresses the pointer of the reference.

Here an example for pointers to pointers to instancePointer.

	NSObject *instancePtr = [[NSObject alloc] init];
	NSObject **ptrToInstancePtr = &instancePtr;
	NSObject ***ptrToPtrToInstancePtr = &ptrToInstancePtr;

Good… I think that is enough about the difference of objective c pointers and java references. Objective c pointers are much more powerful than java references, since c allows the developer to deal with pointers directly.

01 – About this series

February 21, 2011

Java versus Objective C

A few weeks ago i decided do write my first iPhone app. I thought it might be not so hard, since i am a really good java developer. But i was wrong. It is not easy to write your first iPhone app! To be able to write objective c apps, a java developer has to know a view things. If he is familar with them, he can work really well based on Objective-C. But without them, he will be disappointed quite fast.

So i decided to write this blog which should demo the problems i faced, and should help you to speed up the process of learning Objective-C based on java knowledge.

This blog-series is NOT a complete tutorial to learn Objective-C. (See developer.apple.com) Rather than it focuses an the difference between java and Objective-C and should help you to avoid getting into semantic traps.

The different issues of this blog are linked to the developer.apple.com website issues, which might give you a deeper understanding of the sections.

During the next weeks i am going to add more and more issues to this blog series.

02 – Defining Classes

February 21, 2011

Javaclass


In this part of the “java versus objective c” post-series, i’ll give you a very brief introduction into the difference of defining classes based on java and objective c. This part is not a complete tutorial to learn Objective-C. But it is a short overview how Objective-C classes are defined.

The following image shows a very common java class implementation.

It consists of 4 different parts.

  1. a package name
  2. the class definition
  3. definition of instance variables
  4. definition of an instance method

Thats all we have to do for specifying a java class.

Objective C class

(developer.apple.com)

To define exactly the same class using Objective-C, we have to create 2 different files. A header file and an implementation file.

MyClass.h

If methods or variables should be accessible by other classes, you have to define them in the header file. Otherwise the compiler would send an warning.

The header file is the common interface of this class.

Package

The MyClass.h shown in the image above contains nearly the same information as the java class, except the package. ObjectiveC classes are not seperated in hierarchical package structures like java classes. To avoid duplicate Objective-C classnames, they likely use characters in front of the class name to seperate them. For instance NS.. (NSObject, NSString,…) is used to mark core classes from the Foundation.framework and means NextStep. UI.. for classes from the UIKit.framework.

Class definition

The super type of a class definition is separated by a colon.

@interface MyClass : NSObject

Variables

Instance variables are defined in brackets directly after the class definition.

NSInteger intValue;
NSString *stringValue;

If you’d like you can add a visibility marker to instance variables. (See developer.apple.com) By default, the variables are marked with @protected.

@private, @protected, @public and @package. The semantics of this modifiers is the same as in java.

@protected
NSInteger intValue
@private
NSString *stringValue;

Methods

Methods have to be defined outside the brackets of the class definition.

As in java, methods can be instance methods or static class methods. The first character of the method defines its type.

  • “+” means static class method
  • “-” means instance method
-(void) doSomething:(NSInteger) intValue stringValue:(NSString *) stringValue;

If you are dealing with Objective-C methods for the first time, they will be really confusing. Objective-C tries to be as fluent as possible. So the parameters of the method are not seperated by comma but by words.

The following example should give you an idea how this works.

Javamethod


The method

replaceIntegerByValueInString(int arg1, int arg2, String arg3)

will replace all characters matching arg1 by arg2 in String arg3.

Using java, you are separating the parameter by comma.

Unlikely in Objective-C, you are using a different syntax to define methods, as shown in the following image.

Objective-C method

The parameters are separated by words and not by comma. This allows you a very fluent way of calling methods (sending messages to objects).

"Methodcall in Objective-C":
[self replaceInteger:2 byValue:3 inString:@"Using number 2!"];

"Methodcall in Java":
this.replaceIntegerByValueInString(2, 3, "Using number 2!");

MyClass.m

MyClass.m contains the implementation of MyClass.h.

Variables

Instance variables can not be defined in an implementation class since they are declared in the interface.

For further informations about how to define variables, static variables, properties and constants, i am going to write a separate post in a view days.

Methods

You have to implement all the methods defined in the interface. Otherwise you will get a compiler warning: “Incomplete implementation.”

Additionally you can add local methods which are not declared in the interface file. These methods are only visible inside the current class file.


Follow

Get every new post delivered to your Inbox.