Cocoa

This is the third and final post in a series reviewing the book Cocoa Programming, by Aaron Hillegass. Here are links to the first and second parts of this review.

In this post I’ll review a few highlights of the book as well as offer a few suggestions (from my perspective) for improvement should another edition be forthcoming. Let’s begin with the highlights.
Read more »

This post is the second in a series reviewing the book Cocoa Programming, by Aaron Hillegass. This part of the review is dedicated to a closer look at the code examples.

Starting from Chapter 2, the book dives into building relevant code examples. Working with Xcode and Interface Builder, you’ll quickly become familiar with the interface and interaction among both tools. There is even a short segue into the basics of debugging in Chapter 3.
Read more »

This post is the first in a series reviewing the book Cocoa Programming, by Aaron Hillegass.

Let me begin by saying, Aaron’s know the topic of Cocoa programming. As a previous employee of NeXT which merged with Apple, Aaron has extensive experience teaching developers, including many Apple Engineers, how to write applications for Mac OS X.
Read more »

Note: What follows is another post in an on-going series for developers who are interested in learning to write applications for the iPhone. More information about writing for the iPhone can be found here: iPhone Developer Tips .

First off, it’s worthing clarifying that much of what is covered here is as much Cocoa as it is Objective-C. However, since the two are quite closely tied when it comes to developing Mac/iPhone applications, I’ve decided to keep with the Objective-C theme as it relates to the title of this and subsequent posts.

This post will review some of the nuances of memory management. I won’t go into all the details of memory management (see Objective-C Programming Guide , Cocoa Fundamentals and Memory Management Programming Guide for Cocoa ), rather, I’ll point out some of the more subtle concepts to keep in mind as you begin to work with objects.

Object Ownership

Rule #1 – If you create an object using alloc or copy, you need to free that object.
Rule #2 – If you didn’t create an object directly, don’t attempt to release the memory for the object.

For instance, here is an object that I “own” given that I’ve called ‘alloc’ to create the object. It’s up to me to release the memory for this object:

  TestClass *ptr = [[TestClass alloc] init];
 
  ...
 
  [ptr release];

Let’s look at two examples where we are not responsible for managing the memory associated with an object. First, when using a factory (aka convenience) methods of a class. For instance:

NSString *str;
str = [NSString stringWithFormat:@"Some string here..."];
NSLog(str);

The second example, is if you call an accessor method that returns an object. Assume that the object TestClass below has a getter method that returns a pointer to an instance variable named firstName that is an NSString.

  NSString *str;
  // No need to release this object
  str = [TestClass firstName];

This makes sense if you think about it. The getter simple returns a reference (pointer) to an existing object. Now, if you want to retain (express an interest in the object to keep it around) then you would need to use ‘retain’ to bump the reference count. However, if we simply want a pointer to the object as shown here, we don’t have responsibility to release the object.

Initializing Objects

The order of things happening when initializing an object is of great relevance. For example, look at this block of code:

  TestClass *ptr = [TestClass alloc];
  [ptr init]
 
  // Do something with the object
  if (ptr)
    ...

Seems harmless enough, right? Allocate an object and send a message to initialize the object. Here’s the problem, if the init method returns nil (which all good initializers do upon failure to properly initialize an object), the code on line 5 would pass the test (that is, ptr would not be nil).

Now compare that with this approach:

  TestClass *ptr = [[TestClass alloc] init];
 
  // Do something with the object
  if (ptr)
    ...

In the code above, assuming the init method returns nil upon failure, ptr will be set to nil, and the code on line 4 would not pass the test. Much better.

So, the lesson here is twofold: always return nil from an initializer method when the method fails to properly initialize the object. Second, it’s a good practice to combine a call to alloc and init into one step. We’ll talk more about initializers in a separate post.

Releasing Objects

Let’s talk about the other end, releasing objects. Have a look at the implementation for a simple class:

#import "TestClass.h"
 
// ================================
// = Implementation for TestClass =
// ================================
@implementation TestClass
 
-(NSString *) str
{
  return str;
}   
 
-(void) setStr:(NSString *)input
{
  [input retain];
  [str release];
  str = input;
}
 
-(void) dealloc
{
  [str release];
  [super dealloc];
}
 
@end

Look at the code below that creates an instance of the TestClass, calls the setter method to initialize the ‘str’ instance variable, and releases the memory for the ‘ptr’ object.

#import "TestClass.h"
 
int main(int argc, const char * argv[])
{
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 
  TestClass *ptr = [[TestClass alloc] init];
  [ptr setStr:@"Fubar"];
 
  [ptr release];
  [pool drain];
  return 0;
}

The dealloc method in TestClass releases the memory for the ‘str’ instance variable, and it seems all is well. However, if at some point, somewhere inside the class implementation an attempt was made to check if the ‘str’ instance variable is nil (prior to doing some operation) for example:

if (str)
  do something...
else
  do something else...

the if statement would pass and the code on line 2 would be run. Not a good thing.

A better way is to replace the call to release with a call to the setter method and pass in nil . Look at the dealloc method below:

-(void) setStr:(NSString *)input
{
  [input retain];
  [str release];
  str = input;
}
 
...
 
-(void) dealloc
{
  [self setStr:nil];
  [super dealloc];
}

The reason this works is that you can send a message to a nil object without raising an exception. If you follow the trail you’ll see inside the setStr method that the variable ‘input’ (which is nil) is sent a message to retain . This is effectively ignored, as the object is nil . The next line releases the string ‘str’. The last line sets ‘str’ to the value of the input parameter (which is nil ). This prevents the problem in the previous example where ‘str’ still had a reference to a location in memory (even though the memory had been released).

As I was getting familiar with this, I wrote a short example in Xcode. Here is the test block for the dealloc method:

-(void) dealloc
{
  NSLog(@"Address of 'str' before release is: %ld", str);
 
  // After this, 'str' still points to a memory location
  [str release];
 
  // After this, 'str' will be nil  (** This is the preferred approach **)
  //[self setStr:nil];
 
  NSLog(@"Address of 'str' is after release is: %ld", str);
 
  // Notice the result of this based on how the instance var 'str' is released (above)
  if (str != nil)
    printf("'str' still points to a memory location (after being released)!");
  else
    printf("'str' now points to nil.");        
 
	[super dealloc];
}

Notice in this case that line 6 uses release. See the output below:

Now, if you comment out line 6 and remove the comment from line 9, you’ll get the following output. Notice how the reference to ‘str’ after is 0 (nil).

You can download the Xcode project here if you’d like to take a closer look at the complete example. Hopefully this information will save you some time trying to track down an elusive memory leak.

In part 1 of this series I demonstrated how to create a short Java application in NetBeans that communicated, using AppleScript, to the Mac apple event system. The application was a no thrills look into how to invoke the TextEdit application. Despite the brevity of the application it provided the foundation for this next tip, which will build on the ideas to create something a little more salient, as in, something that you might actually find yourself using.

The gist of the application is to instruct iTunes to play a random song, move to the next song, pause, etc. I” onclick=”return TrackClick(”,’javascript%3AlynkVideoPop%28719%2C’)”ll show one use of the application by wrapping the code into a bash script that allows you to invoke the program (and all commands) from within a terminal. Watch the video that follows for all the details…

This application is all of about 80 lines, including the bash script. Sometimes a little creative thinking and a few lines of code are all that” onclick=”return TrackClick(”,’javascript%3AlynkVideoPop%28719%2C’)”s needed to write an intriguing (and hopefully useful) application.


The music in the video is Led Zeppelin and the song: Moby Dick. Led Zeppelin at Amazon


A few weeks back I demonstrated how to write Ruby code inside NetBeans to control scriptable applications on a Mac, that is, communicate between Ruby and the Apple Event system. In this post, I will turn things around a bit from the previous post and use NetBeans and Java to execute AppleScript.

There is a subtle difference, in the previous post the focus was on how to write code in Ruby (inside NetBeans) using the rb-appscript bridge. This time around the approach is to work with Java and pass AppleScript code to a set of Cocoa files (classes) that will act as the bridge between our application and the Mac system.

There is one caveat – the Cocoa-Java API is deprecated as of Mac OS X Tiger. The NSAppleScript and NSMutableDictionary classes are still available, however, they are no longer on the development path within Apple. There are scripting bridges that allow you to control scriptable applications using Python, Ruby, and Objective-C. Java Native Interface (JNI) is an additional option to call platform specific code. You can read more about JNI in this technical note: JNI development on Mac OS X.

One more note, if you follow the steps in this video and the classes NSAppleScript and NSMutableDictionary are shown with lines through them (for example, NSAppleScript), this has to do with a preference setting inside NetBeans to show deprecated classes with a strike-through. You can change this as follows: From the Preferences dialog, choose Fonts/Colors; click the Syntax option; from the Language list choose Java; click on Deprecated Element; in the Effects option, choose None.

Join me in Part 2 of this tip where I” onclick=”return TrackClick(”,’javascript%3AlynkVideoPop%28719%2C’)”ll show a more comprehensive (read: interesting) example where it” onclick=”return TrackClick(”,’javascript%3AlynkVideoPop%28719%2C’)”s all about controlling iTunes using Java.


The music in the video is Led Zeppelin and the song: Moby Dick.
Click the image to see more about about Led Zeppelin and the CD (at Amazon)