RSS
 

Objective C for Java Programmers – Part 2

02 Oct

In Objective C, you encounter something that you could remain almost blissfully ignorant of in Java – memory management.

To create an object in Objective C, you need to do two things :

  • allocate memory for it,
  • initialize the data in the object.

In Java, that’s accomplished via the constructor :

User u = new User("Joe","abc123");

In Objective C, it’s accomplished in two steps,

User * u = [[User alloc] init:@"Joe" withPassword:@"abc123"];

the equivalent of (in Java-like syntax)

User u = User.alloc().init("Joe","abc123");

In Objective C, every class has an alloc() method.

When you’re finished with an object in Java, you don’t need to do anything special. When all variables referring to the object vanish from scope (eg, because they are local variables in a method or loop or if statement that you’ve finished), the Garbage Collector will clean up the object and recover the memory.

The good news : Objective C also has a garbage collector, called the Autorelease Pool.

The bad news : The Autorelease Pool in Objective C is a passive beast that only handles objects you give it.

This means that you, the programmer, must take responsibility to ensure that every object created is

  • EITHER, released when not needed (and only when not needed)
  • OR, is passed to the autorelease pool when created

Therefore,

User * u = [[User alloc] init:@"Joe" withPassword:@"abc123"];

is a recipe for disaster. Instead, you should use

User * u = [[[User alloc] init:@"Joe" withPassword:@"abc123"] autorelease];

And even this doesn’t quite solve the problem.

You will need to develop some strongly-entrenched habits to avoid memory leaks. For a Java programmer, memory leaks are a rare, curious kind of bug. Like wolves for a resident of New York. You have to go to considerable effort to get eaten by one. Not in Objective C. Memory leaks are now like wolves for a medieval village. A constant danger, always lurking, held at bay only by good habits carefully nurtured and maintained. Welcome to the 15th century.

There’s two excuses Objective C to behave like this.

  • Objective C is a much older language than Java, dating back to the 1980’s, when explicit memory management was the norm
  • Steve Jobs fills good and bad ideas alike with wonderful glamour and glitter. Like Disney. Were you surprised when they bought Pixar?

 

 
 

Tags: , , , , ,

Leave a Reply