Beliebte Suchanfragen

Cloud Native

DevOps

IT-Security

Agile Methoden

Java

//

Short Introduction to iOS for Java Developers: Objective-C

18.4.2011 | 6 minutes of reading time

For Java developers starting iOS development, the hardest shift will probably be the Objective-C, the Apple’s language of choice. The Objective-C is extension of the standard ANSI C language, providing syntax for defining classes and methods, and other object oriented constructs. So any experience with C will help you a lot. In fact, since Objective-C is a superset of the ANSI version of the C, you’ll need to know the basics of C before learning Objective-C.

Unlike in Java, where you define and implement class in one file, in Objective-C you have two files. Same as in C, you have header files (.h) for public declarations and source files (.m) for implementation, which can hold both Objective-C and C code. You can even use C++ if you want (.mm files). The following example shows DeathStar class implemented in Java and Objective-C.

DeathStar.java

1import com.empire.Jedi;
2import com.empire.SpaceShip;
3import com.empire.SuperWeapon;
4 
5public class DeathStar extends SpaceShip implements SuperWeapon {
6 
7    private boolean complete;
8    private Integer power;
9 
10    public boolean isComplete() {
11        return complete;
12    }
13 
14    public void setComplete(boolean complete) {
15        this.complete = complete;
16    }
17 
18    public Integer getPower() {
19        return power;
20    }
21 
22    public void setPower(Integer power) {
23        this.power = power;
24    }
25 
26    public static void turnToDarkSide(Jedi jedi) {
27        //...
28    }
29 
30    public void destroyPlanet() {
31        //...
32    }
33 
34    @Override
35    public void lockTargetAt(int xCoord, int yCoord) {
36        //...
37    }
38 
39    @Override
40    public boolean fire() {
41        // ...
42        return true;
43    }
44}

In Objective-C it would look like this:

DeathStar.h

1#import "SpaceShip.h"
2#import "SuperWeapon.h"
3#import "Jedi.h"
4 
5 
6@interface DeathStar : SpaceShip <SuperWeapon> {
7    BOOL completed;
8    NSNumber *power;
9}
10 
11@property(nonatomic, assign) BOOL completed;
12@property(nonatomic, retain) NSNumber *power;
13 
14+ (void)turnToDarkSide:(Jedi *)jedi;
15- (void)destroyPlanet;
16 
17@end

DeathStar.m

1#import "DeathStar.h"
2 
3 
4@implementation DeathStar
5 
6@synthesize completed;
7@synthesize power;
8 
9 
10-(void)dealloc {
11    [power release], power = nil;
12    [super dealloc];
13}
14 
15- (void)destroyPlanet {
16    //...
17}
18 
19+ (void)turnToDarkSide:(Jedi *)jedi {
20    //...
21}
22 
23 
24#pragma mark -
25#pragma mark SuperWeapon
26 
27- (void)lockTargetAtX:(NSInteger)xCoord andY:(NSInteger)yCoord {
28    //...
29}
30 
31- (BOOL)fire {
32    //...
33    return YES;
34}
35 
36@end

Protocols

In the example we can see that DeathStar class extends SpaceShip and conforms to the SuperWeapon protocol. A protocol declares methods that can be implemented by a class. They simply define an interface that other objects are responsible for implementing. When a class implements methods of a protocol we say that the class conforms to that protocol. Protocols can have optional and required methods. The Objective-C protocols are something similar to Java interfaces. In fact, it’s said that Java interfaces where inspired by protocols. Protocols are used frequently to specify the interface for delegate objects. Delegate pattern is massively used in iOS development, so you should get familiar with it. Here is the declaration of the SuperWeapon protocol:

SuperWeapon.h

1@protocol SuperWeapon
2 
3- (void)lockTargetAtX:(NSInteger)xCoord andY:(NSInteger)yCoord;
4- (BOOL)fire;
5 
6@end

And here is the Java counterpart:

SuperWeapon.java

1package com.empire;
2 
3public interface SuperWeapon {
4    void lockTargetAt(int xCoord, int yCoord);
5    boolean fire();
6}

Properties

Objective-C supports both strong and weak typing. For example:

1NSNumber *power; // strong typing
2id       power; // weak typing

In Objective-C object references are pointers. You have to remember to put the * in front of the variable names for strongly-typed object declarations. The id type implies a pointer. So this is quite different from Java, but if you have some experience with C, you should be familiar with this.

Declared properties are a convenience notation used to replace the declaration and, optionally, implementation of accessor methods. This is something extensively used, and very much recommended. This will also help you with the memory management, which will talk about later.

1@property(nonatomic, retain) NSNumber *power;

Properties are declared with @property directive, followed by and optional options, followed by a type and name. In your class implementation, you can use the @synthesize compiler directive to ask the compiler to generate the accessor methods according to the specification in the declaration.

1@synthesize power;

The given attributes in the example specifies that retain should be invoked on the object upon assignment (we’ll talk more about this in memory management) and that property is nonatomic. By default properties are atomic so that synthesized accessors provide robust access to properties in a multithreaded environment (Remember, Objective-C is used also for Mac OS X development).

Those two lines of code in Java would look like this:

1private Integer power;
2 
3    public Integer getPower() {
4        return power;
5    }
6 
7    public void setPower(Integer power) {
8        this.power = power;
9    }

More about properties and declaration attributes you can read here .

Methods and Messaging

A class in Objective-C can declare two types of methods: instance methods and class methods, marked by -/+:

1+ (void)turnToDarkSide:(Jedi *)jedi;
2- (void)destroyPlanet;

Class methods are like static methods in Java. You call a method by messaging an object. A message is a method signature with the parameters. Messages are dispatched dynamically. Messages are enclosed by brackets, with the object receiving the message on the left side and the message (along with any parameters required by the message) on the right.

1[self destroyPlanet];
2[DeathStar turnToDarkSide:jedi];

In Java this would look like:

1this.destroyPlanet();
2DeathStar.turnToDarkSide(jedi);

That’s another big syntax difference from Java. The exception are accessor methods which use standard dot syntax:

1self.power = 60;

In Java:

1this.setPower(60);

You can also target a method by using selectors which can be useful when handling events. Selectors are like pointers to a method. This is something that Java does not have.

1[[UIBarButtonItem alloc] initWithImage:image
2                         style: UIBarButtonItemStylePlain 
3                         target:self
4                         action:@selector(destroyPlanet)];

The Memory Management

While there is a Garbage Collector that you can use for OS X application, for iOS you must manage your memory manually. This is probably the most difficult thing to get used to for Java developers. You should try to ensure that your application does not use more memory than necessary, since memory is usually scarse resource in mobile devices. Objects should be destroyed when they are no longer needed, but it is also important that you do not destroy objects that are still used. Cocoa defines a mechanism by which you can specify when you need an object and when you have finished with it. It’s called object ownership.

Any object may have one or more owner. As long as an object has at least one owner, it continues to exist. If an object has no owners, the runtime system destroys it automatically. You only release or autorelease objects you own.

  • You own any object you create (alloc, copy, new)
  • You can take ownership of an object using retain
  • You must relinquish ownership of objects you own when you’re finished with them (release)
  • You must not relinquish ownership of an object you do not own

Tip: Class methods by convention own the returning objects, so you do not release them.

The ownership policy is implemented through reference counting or “retain count”. Each object has a retain count.

  • When you create an object, it has a retain count of 1.
  • When you send an object a retain message, its retain count is incremented by 1.
  • When you send an object a release message, its retain count is decremented by 1.
  • When you send an object a autorelease message, its retain count is decremented by 1 at some stage in the future
  • If an object’s retain count is reduced to 0, it is deallocated

Tip: Use properties, they simplify the memory management.

While in Java you create an object and can forget about it (leaving it to Garbage Collector):

1Jedi jedi = new Jedi();

in Objectiv-C you have to allocate memory for it, initialize it, and destroy it after you’ve finished with it:

1Jedi *jedi = [[Jedi alloc] init]; // create the Jedi
2[DeathStar turnToDarkSide:jedi]; // turn Jedi to the dark side
3[jedi release], jedi = nil; // destroy the Jedi

More about memory management you can read here :

You can find short introduction to Objective-C here .
More detailed overview of Objective-C can be found here .

Previous: SDK | Next: MVC

share post

Likes

0

//

More articles in this subject area

Discover exciting further topics and let the codecentric world inspire you.

//

Gemeinsam bessere Projekte umsetzen.

Wir helfen deinem Unternehmen.

Du stehst vor einer großen IT-Herausforderung? Wir sorgen für eine maßgeschneiderte Unterstützung. Informiere dich jetzt.

Hilf uns, noch besser zu werden.

Wir sind immer auf der Suche nach neuen Talenten. Auch für dich ist die passende Stelle dabei.