Aug 13, 2008

iPhone Developer Tips…Now Online!

If you’ve been reading the iPhone related tips on this site, you’ll want to point your browser to my new iPhoneDeveloperTips.com blog!

I’ll continue to write tips here as well, however, the primary focus of my career is now iPhone centric, so the bulk of my writing will focus on the iPhone.

To get things rolling on the iPhone blog, I have migrated the iPhone tips shown here to the new blog. If you are the author of any comments on iPhone tips that started on this site, and have a few minutes to spare, I would encourage you to copy/paste your comments onto the new blog.

For the iPhone developers in the crowd, I hope you find the new site a valuable resource.

John

Aug 12, 2008

iPhone Developer Tips Coming Soon…

I’ve been getting a great deal of interest in the iPhone developer tips section of this blog. So much that I’ve decided to move all iPhone centric tips to another blog, you guessed it, iPhoneDeveloperTips.com.

If you have ideas, suggestions or questions that might make for good iPhone tips, pass along your thoughts by commenting here or dropping me an email.

This blog won’t vaporize, however, I am in the midst of a transition after nearly 8 years in mobile development with J2ME to move the iPhone, so the pace may slow a bit.

If you are involved in working with the iPhone or Xcode as a developer, author of a book, trainer/courseware development or otherwise working on the iPhone, send me an email if you are interested in exploring the possibility of a partnership or other opportunities for working together. It’s been a good run with J2ME, where I’ve had the opportunity to work with many of world’s most prominent names in the mobile device business. I’m ready for what’s next, and this time around it’s all about the iPhone!

Aug 8, 2008

Objective-C: Where is My Object Retained?

Apologies for the gap since my last post. It’s been a long week as my wife and I were in a serious car accident a week ago today. I’ll spare the details, however, let it suffice to say that our vacation plans didn’t include all the drama that unfolded that day. We are both on the mend and have plans for a full recovery. Let’s get back into it…

For those new to Objective-C and iPhone development, I want to point out something that might save you some time. Look at the code below:

@interface SomeClass : UIViewController
{
  ..
	UIView *containerView;
  ...
}
@implementation SomeClass
...
- (void)loadView
{
  ...
  UIView *uiView = [[UIView alloc] initWithFrame:
     [[UIScreen mainScreen] applicationFrame]];
  self.containerView = uiView;
  [uiView release];
  ...
}
...
@end

In this block of code, I am setting up a container view, that will hold several subviews. Once the assignment is complete on line 8, I release the local object uiView. Question is, how I can I get away with releasing the variable and still have access to the view in the SomeClass object? In other words, where is the retain?

First thing to notice is that the dot syntax is shorthand for accessing class instance variables using Objective-C properties. If one were to write the code without using properties (and thus, no dot syntax) the answer is obvious.

For example, the equivalent code directly calling the accessor (setter) method would look as follows:

[self setContainerView:uiView];
[uiView release];

At this point, if one was curious about where the object was retained (before the release), the obvious place to look is inside the setter, which might look as follows:

- (void) setContainerView:(UIView *) view
{
  [view retain];
  [containerView release];
  containerView = view;
}

Easy enough, the object is retained as part of the setter. What we have here is a good example of pro’s/con’s when working with properties. On one hand, properties allow for simplification and consistency in our code. On the other hand, if using properties and we request the compiler to implement the getter/setter methods (through use of the @synthesize directive) there is code created for us to implement these methods, which we never see.

Although properties are no doubt handy, as this example illustrates, it’s important to understand what is happening behind the scenes. A clear picture of the little nuances can go a long ways when it comes to debugging a thorny problem.

Jul 29, 2008

UIKit: NSIndexPath and row method

In working with the SimpledDrillDown example in the iPhone SDK, I was walking through the code in the RootViewController class. The interface definition is shown below:

@interface RootViewController:UITableViewController
{
DataController *dataController;
}

There is a method inside the class that looks as follows:

- (void)tableView:(UITableView *)tableView
  didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
...
detailViewController.detailItem = [dataController objectInListAtIndex:indexPath.row];
...
}

The last parameter to this method ‘indexPath’ is of type NSIndexPath . Now if you look at the class reference for NSIndexPath , you won’t find the ‘row’ method shown above? What’s up with that?

This is actually a great example of Objective-C categories in use (here is a link to a previous post on categories) The UIKit has extended the NSIndexPath class (without subclassing) through use of a category. The reason for this addition is to add support for identifying rows and sections in UITableView objects.

The addition consists of a class factory method indexPathForRow:inSection: which creates an NSIndexPath object when passed in row and section values. There are also two properties available to return the row index number and the section index number.

You can find all the specifics in NSIndexPath UIKit Additions .

Jul 25, 2008

Objective-C: Alternative Use of Properties?

While scanning a few code examples inside the iPhone SDK, I bumped into something interesting. I wrote a short example to mimic what I found…take a look at the following interface declaration:

@interface SomeClass : NSObject
{
  NSString *str;
  NSDate *date;
} 
 
@property (nonatomic, retain) NSString *str;
@property (nonatomic, retain) NSDate *date;
@property (readonly) NSString *testSomething;

The only aspect that should standout is the property declaration for testSomething . Notice there is no instance instance variable tied to this declaration. This is different if for no reason other than the typical use for properties is as a shorthand for declaring accessor methods for instance variables.

So what happens if we now add an instance method, such as shown below, inside the implementation file for SomeClass (and don’t include either a @synthesize or @dynamic declaration)?

- (NSString *) testSomething
{
  return @"Foo";
}

Well, for one thing, we can now access the testSomething method using dot syntax.

SomeClass *ptr = [[SomeClass alloc] initWithStrAndDate:@"Fubar"];
...
NSLog(@"test: %@", ptr.testSomething);

This is intriguing. I couldn’t find any specific references to using properties in this manner. Is this simply a side-effect of how properties are implemented?

If you can shed any light on this, including whether this is a common/good practice, please post a comment.

Jul 24, 2008

Objective-C: Properties, Setters and Dot Syntax

I’ve been ramping up on iPhone development, and with the NDA still in place (as far as I know), I haven’t been able to blog about what I’ve written/learned. And with that, it’s been quiet in here. Too get back into this, let’s continue to spend some more time on Objective-C…

The properties feature in Objective-C is your friend. Once you’ve written a few classes and manually wrote the accessors (getters and setters), you’ll quickly understand why properties are a good thing.

In addition to automatic creation of getters/setters, there is an option to use dot syntax in place of the traditional [receiver message] format.

I want to point out one little nuance when working with properties, setters and dot syntax , that I didn’t find to be particularly intuitive.

Let’s say you have a class with an interface definition such as this:

@interface SomeClass : NSObject
{
  NSString *str;
  NSDate *date;
} 

@property (nonatomic, retain) NSString *str;
@property (nonatomic, retain) NSDate *date;
...

The implementation file might look like this:

@implementation SomeClass

@synthesize str;
@synthesize date;

...

Using this approach, with the combination of @property and @synthesize, we now have getters/setters that are automagically created for you. You can call them as expected

// Call the getter
NSLog(@"The value is: %s", [ptr str]);

// Call the setter
[ptr setStr:@"fubar"];

Using dot syntax, here is what a call to the getter would look like:

// Call the getter
NSLog(@"The value is: %@", ptr.str);

This syntactic sugar is quite handy and easy to grasp, for the most part (even more so if you come from languages such as Java).

Everything is pretty much as expected up to this point. The whole reason for this tip is to callout the syntax for the setter when using dot syntax. Logic tells me, it should look as follows:

// Call the setter, well on second thought, maybe not
ptr.setStr = @"Testing this";

Seems reasonable doesn’t it? It effectively matches the setter method of the [receiver message] approach. However, the correct syntax is:

// Call the setter
ptr.str = @"Testing this";

The first time I ran across a setter used this way I stopped, scratched my head a few times, scrunched up my face and probably mumbled something along the lines of "what the…"

As you dig deeper into Objective-C, and even more so, as you look into the examples that are included with the iPhone SDK, you’ll want to make note of this, as properties are used extensively throughout the code.

The format (for the setter) when using dot syntax takes some getting used to. However, hopefully this little tip will clear up the confusion until you are used to seeing this style of setter.

Jul 14, 2008

iPhone SDK – Final Release

Looks as though the final release of the iPhone SDK is now available. Although there seems to be little fanfare with the transition from beta, this is a milestone none the less.

I’ve downloaded and installed the SDK and have noticed a few minor changes, from fixes in Xcode to some updated documentation and examples.

Up to this point, anything that I’ve written in regards to the iPhone has been around laying the foundation for learning to build iPhone applications, that is, information that is not specific to the iPhone SDK. Unfortunately, from comments to my original post here (to other resources on the net) even though the iPhone SDK is no longer in beta, the NDA still applies. Put another way, looks like the wait continues until I can post code examples, tips and tricks as it applies specifically to iPhone development.

On a related note, I will have to say that I am impressed with the developer related documentation that Apple has published for Cocoa to MVC to Xcode. In all my years of development, often times my experience has been that this is one areas that lacks, fortunately, not this time around.

I was having a discussion recently with a friend whom I am collaborating with to ramp up on iPhone programming. He made an interesting comment that the barrier of entry to iPhone development is pretty high. It’s not that Objective-C is difficult to learn, or that the SDK or tools are lacking, it’s really more about the transition to Cocoa development in general. For example, with Google and Android, the potential developer audience is huge (there is no Java support on the iPhone).

Honestly, I think this is a good thing for those who take on this challenge. Assuming the iPhone continues to gain market share, and businesses and consumers begin migrate to custom applications created for the device (think Apple’s App Store), this can only be a good thing for those of us who are focused on building iPhone applications.

Jul 11, 2008

CocoaHeads MN: Objective-C

Lastnight was the second meeting for CocoaHeads in Minnesota .

The meeting was all about Objective-C. Bob McCune , the organizer of the event, gave a talk that covered Objective-C from beginning to end. One of the most intriguing aspects (at least from my perspective) was how the group would segue into a discussion on a topic. What was quite helpful was insight from those in the group who had significant experience working with Cocoa and Objective-C.

Bob did an excellent job, covering a great deal of ground, and wrapped up with an demo of a calculator application that tied together many of the concepts. If you are new to working with protocols, I highly recommend you download and give the application a look. The example shows how you can define and implement a protocol – no better way to learn a concept than to see it in code (I’ll add a link to the code once it is posted on the MN CocoaHeads site).

Many thanks to Bob McCune for starting MN CocoaHeads , Synergy Information Systems for making the space available, and Vladan Pulec (Synergy) for adding a link to this blog from the CocoaHeads MN website.

If you live in Minnesota, are within reasonable driving distance to Bloomington (or even if not) and are interested in developing applications for the Mac/iPhone, join us on August 14th (the second Thursday of every month) for our next meeting.

Jul 2, 2008

Objective-C: Private Methods

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

One common complaint for many new to Objective-C is that the language lacks support for private methods within a class. There are compiler directives for instance variables: @private, @protected (the default) and @public. However, if you want to hide methods, there is no specific directives to help. The example here builds on the previous post on working with categories.

Ultimately, there is no means to make a method private in Objective-C. However, one can hide methods in a class as I show here. It’s important to understand, this still does not make the methods private, it just makes them “harder to find” if you will.

To implement hidden methods (instance and/or class) you can use categories . Let’s begin with a file called SomeClass.h, the interface definition for SomeClass.

// ===========================
// = File: SomeClass.h
// = Interface for SomeClass
// ===========================
 
@interface SomeClass : Object
 
-(void) msg;
+(void) classMsg; 
 
@end

Nothing too interesting here, simply an interface declaration for a class with two methods: msg and classMsg . By definition (of the language) both methods are publicly accessible. Now, let’s look at the corresponding implementation file shown below. Begin at the bottom where I write the implementation for the two methods above. Again, nothing new, so far. Now, if you start at the top of this file, notice how I’ve added an interface for SomeClass (similar to the interface definition above), however, I added (hidden) to the definition, which now makes the interface definition a category. Just below the definition, I write the code for the two methods in the category.

// ===========================
// = File: SomeClass.m
// ===========================
#import "SomeClass.h"
 
// =================================
// = Interface for hidden methods
// =================================
@interface SomeClass (hidden)
 
+(void) hiddenClassMethod;
-(void) hiddenInstanceMethod; 
 
@end
 
// =====================================
// = Implementation of hidden methods
// =====================================
@implementation SomeClass (hidden)
 
+(void) hiddenClassMethod
{
  printf( "Hidden class method.\n" );
}
 
-(void) hiddenInstanceMethod
{
  printf( "Hidden instance method\n" );
}
 
@end
 
// ================================
// = Implementation for SomeClass
// ================================
@implementation SomeClass
 
-(void) msg
{
  printf("Inside msg()...\n");
 
  [self hiddenInstanceMethod];
  [SomeClass hiddenClassMethod];
}
 
+(void) classMsg
{
  printf("Inside classMsg()...\n");
}
 
@end

To see what this does for us, look at the code below, followed by the screenshot:

// ===========================
// = File: Main.m
// ===========================
#import "SomeClass.h"
 
int main (int argc, char *argv[])
{
  SomeClass *ptr = [[SomeClass alloc] init];
 
  // Display message (including messages from hidden methods)
  [ptr msg];
 
  // Call a class method
  [SomeClass classMsg];
 
  // Compile warning (can't access hidden instance method)
//  [ptr hiddenInstanceMethod];
 
  // Compile warning (can't access hidden class method)
//  [SomeClass hiddenClassMethod];  
 
  return 0;
}

Notice how I can access the hidden instance and class methods from within the class. However, if I remove the comments from lines 17 and 20, to attempt access to the hidden methods, the compiler generates the following warnings:

I’m not sure if this is the only means to hide methods. If you know of another way (and have a code example), please post a comment.

The output of the application is shown here:

Download the code and give this a try within Xcode.

Jul 1, 2008

Objective-C: Categories

As an alternative to subclassing, Objective-C categories provide a means to add methods to a class. What’s intriguing, is that any methods that you add through a category become part of the class definition, so to speak. In other words, if you add a method to the NSString class, any instance, or subclass, of NSString will have access to that method.

Defining a category is identical to defining the interface for a class, with one small exception: you add a category name inside a set of parenthesis after the interface declaration. The format is shown below:

@interface ClassToAddMethodsTo (category)
  ...methods go here
@end

For example, below I’ve defined a category that adds a method to the NSString class. The method reverseString adds the capability to all NSString objects to reverse the characters in the string.

@interface NSString (reverse)
-(NSString *) reverseString;
@end

As with the @interface declaration, the @implementation section changes only in that the category name is added to the definition. Below is the implementation of the interface defined above. Notice how in both cases I added (reverse) , which is the category name I assigned.

@implementation NSString (reverse)
 
-(NSString *) reverseString
{
  NSMutableString *reversedStr;
  int len = [self length];
 
  // Auto released string
  reversedStr = [NSMutableString stringWithCapacity:len];     
 
  // Probably woefully inefficient...
  while (len > 0)
    [reversedStr appendString:
         [NSString stringWithFormat:@"%C", [self characterAtIndex:--len]]];   
 
  return reversedStr;
}
 
@end

What follows is a short example to showing how one might use the above category.

#import <Foundation/Foundation.h>
#import "NSString+Reverse.h"
 
int main (int argc, const char * argv[])
{
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  NSString *str  = [NSString stringWithString:@"Fubar"];
  NSString *rev;
 
  NSLog(@"String: %@", str);
  rev = [str reverseString];
  NSLog(@"Reversed: %@",rev); 
 
  [pool drain];
  return 0;
}

The output of the above example is shown here:

Overriding Methods

Categories can also be used to override methods the class inherits, again, providing an alternative to subclassing. You can always access the overridden method using super . I would assume from an internal (compiler/code generation) perspective, this could lead to less code/overhead as compared to creating a subclass solely to override a method (caveat: I have no proof that is true).

Dividing Source Code into Separate File

Although I haven’t given this a go, categories provide an interesting opportunity to disperse the implementation of a class across one or more files. The Objective-C Programming Guide lists several benefits of this including:

  • Opportunity to group together methods that perform similar tasks.
  • Configuring classes differently for various applications, yet maintaining one set of code.

Naming Conventions

The recommended naming convention for a category is “ClassToAddMethodsTo+CatgoryName” for instance, I used the following filenames for the interface and implementation of the above category code:

  • NSString+Reverse.h
  • NSString+Reverse.m

Caveats

You cannot add instance variables to a class through a category. Also, category names must be unique across an application.

Source Code

I’ve attached the Xcode project for the above example if you’d like to give it a try.

In the next post I’ll show another example of using categories – the example will show one approach for hiding methods within in a class, as Objective-C does not offer support for private methods.

Jun 30, 2008

Objective-C: Initializers

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

The code for creating new instances of a class generally looks as follows:

  SomeClass *ptr = [[SomeClass alloc] init];

In this case, we send a message (alloc) to the recevier (SomeClass) to create a new instance; the object returned from this message, then sends a message (init) to initialize instance variables within the class.

I briefly talked about the importance of the order in which objects are allocated and initialized. You can read more about that here: Memory Management in Objective-C . In this post, I want to introduce how to override the init method of the NSObject class, more specifically, how to work with multiple initializers.

In the init method of the NSObject class, no initialization takes place, it simply returns self .

The basic format of a method to override the initializer looks as follows:

-(id)init
  {
    if (self = [super init])
    {
      // Initialization code here
    }
    return self;
  }

It’s important to call the super init method first to ensure that instance variables up the inheritance hierarchy are initialized in the proper order (from top to bottom). Also, if your initialize code fails, you need to return nil from the overriden init method. Finally, return a reference to self as shown above.

So let’s assume we have a block of code as follows:

  SomeClass *ptr = [[SomeClass alloc] init];
  [ptr setStr:@"Testing"];

Here we initialize a new instanc of SomeClass, and follow this with a call to set an instance variable to the specified string (@”Testing). One common means to accomplish this is to create a new initializer in which we pass in the parameter (the string in this case) as part of the original creation of the object. For example:

  SomeClass *ptr = [[SomeClass alloc] initWithStr: @"Testing"];

We can also take this one step further. Let’s say that we also wanted to initialize an instance variable that was a pointer to a date object (NSDate *). In that case, we might want an additional initilizer that looks as follows:

  SomeClass *ptr = [[SomeClass alloc] initWithStrAndDate:@"Testing"
       date:[NSDate date]];

It quite common for classes to have more than one initializer for creating new objects, allowing variations as shown above. This also implies that the initialization methods need to work in harmony. Designated initializers are the means to achieve this harmonious state.

Designated Initializers
When working with a class that has more than one initialization method (as shown above), it’s important that one of the initializers drives the whole process. Put another way, only one of the initializer methods does the actual work of calling the super class initializer and initializing the instance variables of the object.

This process is actually quite simple. Let’s assume we have a class implementation as follows:

  @interface SomeClass : NSObject
  {
  	NSString *str;
    NSDate *date;
  } 
 
  // Designated initializer
  -(id)initWithStrAndDate: (NSString *)inStr date:(NSDate *)inDate;
  -(id)initWithStr: (NSString *)inString;
  -(id)init;

The way this should work, is that a call to the initializer init should call initWithStr . A call to the initializer initWithStr should call initWithStrAndDate . Following this process, all the actual initialization work occurs in initWithStrAndDate . This method (the one that does the work) is known as the designated initializer .

A general rule of thumb (although not always the case) is that the designated initializer is the initializer with the most parameters.

So let’s see how this might look within the implementation of a class:

  @implementation SomeClass
 
  // ==========================
  // = Designated initializer =
  // ==========================
  -(id)initWithStrAndDate: (NSString *)inString date:(NSDate *)inDate
  {
    if (self = [super init])
    {
      [self setStr:inString];
      [self setDate:inDate];
    }
    return self;
  }
 
  -(id)initWithStr: (NSString *)inString
  {
    // Either of these will work
    return [self initWithStrAndDate:inString date:[NSDate date]];
    //  return [self initWithStrAndDate:inString date:nil];
  }
 
  -(id)init
  {
    return [self initWithStr:nil];
  }
 
  ...
  @end

Notice how starting with init , it calls the next initializer in the chain, initWithStr , passing in a default value (in this case, nil). This method then calls the designated initializer, again, passing in a default value, this time for the date. And notice how the designated initializer is the only method that calls super .

Working with multiple initializers is a simple process of ensuring that each initializer calls up through the initialization chain within the class. This ensures that all instance variables are initialized in just one place, and that the super method is called such that all instance variables of classes further up the hierarchy are initialized first (from top down).

Here is a copy of the Initializers Xcode project if would like to try the above example within Xcode.

Jun 27, 2008

TextMate and Xcode

I’ve been spending time getting familiar with Xcode as I learn to write applications in Objective-C, with the larger goal of writing applications for iPhone. My editor of choice on the Mac up to this point, is TextMate, an great all around code editor. I’ve written a number of tutorials/tips on TextMate on this blog (check out the TextMate Category for links).

One of the things I’ve become quite accustomed to is tabbed based user interfaces. For example, in FireFox I typically have a screenful of open tabs. When working with projects inside of TextMate, you can have multiple source code files open in tabs. Unfortunately, this is not a feature supported in Xcode (that I am aware of).

So, I spent a few minutes poking around at various options and came up with an approach that is far from perfect, yet offers a blend of coding in TextMate and managing compiles/builds in Xcode. Not perfect, however, it’s working for me.

Click on the image below to learn more.

Jun 26, 2008

Objective-C: Memory Management

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.

Jun 24, 2008

Objective-C: Messaging

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

This post introduces messaging within Objective-C. Messaging is the terminology for invoking methods on an object. The format for a message expression is as follows (the brackets are required):

[object method]

or in Objective-C parlance

[receiver message]

Here’s a simple example:

  // Create an instance of SomeClass object
  // We'll cover this later...
  SomeClass *ptr = [[SomeClass alloc] init];
 
  // Send the message 'printInstanceVars' to the 'ptr' receiver
  [ptr printInstanceVars];

If we want to pass an argument as part of the message (that is, pass a parameter to the method), we send a message that looks like this:

[receiver message:argument]

For example, assume setStr and setX are two methods in the SomeClass object and ptr is a pointer an instance of SomeClass . Here is how we might pass arguments to each method.

 [ptr setStr:@"Testing"];
  [ptr setX:2008];

Side note: The @ symbol at the front of @”Testing” string is convenience method that converts the given string to an NSString object, which in the case of the setStr method, is the required type for the parameter.

Nest Messages
We can also nest messages, as shown below. In this example, we first pass a message to the NSDate object. This is a class object with a factory method ‘date’ for creating a new NSDate object. If that makes no sense, don’t worry about it. Think of it as nothing more than creating a new NSDate object that holds the current date and time. The return value of inner message (the NSDate object) is the argument for setDate message. What we’ve done here is to create a new date object and pass it as an argument to the setDate message of the receiver (ptr ). Sounds more confusing than it is.

[ptr setDate:[NSDate date]];

Multiple Arguments
Taking this another step further, we can pass multiple arguments along with our message. The message below takes three arguments, a string, date and integer. Sometimes it easier to read the method aloud to get this jist of what’s up. In this case, “pass a message to the ptr receiver that sets a string, and a date and an integer.”

  [ptr setStr:@"A new test..." andDate:[NSDate date] andInteger:99];

Here is how we define the message in the interface file:

-(void) setStr:(NSString *)str andDate:(NSDate *)date andInteger:(int)x;

And here is the implementation of the setStr() method which accepts three arguments:

-(void) setStr:(NSString *)strInput andDate:(NSDate *)dateInput
    andInteger:(int)xInput
{
  [self setStr:strInput];
  [self setDate:dateInput];
  [self setX:xInput];
}

Let me point out a few things about this method. First, notice how in the definition I used the names str , date and x . However, in the implementation, I used the names strInput , dateInput and xInput . The first thing to understand is that you can do this. The reason for doing so, is that in the class where setStr() is defined, I have instance variables with the names str , date and x . If I didn’t change the names in the actual implementation, I’d get a compiler warning that a local declaration hides an instance variable.

In this code example, the simplest thing to do is to change the variable names in the method to make it obvious what variables are referring to what. This may not be the best naming scheme for your applications, however, I wanted to point out the flexibility as to how you define and implement methods and their arguments. Obviously, do what makes the most sense for your specific needs and at the same time, results in the most readable code.

Also, note that this version of setStr() does nothing more than send a message as follows: the receiver is current object instance (self), the message is a setter method and the argument to each message is the appropriate parameter passed in to setStr() .

Using the format/syntax of Objective-C takes some getting used to. However, once you do, you’ll find that it’s easy to read code that has had some thought put into the names of message and the parameters.

Variable Number of Arguments
The last topic is creating messages with a variable number of arguments. Let’s start with the interface definition of a method that accepts a variable number of arguments:

-(void) printInstanceVars:(id)input, ...;

In this example, I declare on parameter that is of type ‘id’, which can represent any object. The implementation of the method looks as follows:

-(void) printInstanceVars:(id)input, ...
{
  id currentObject;
  va_list argList;
  int objectCount = 1;
 
  if (input)
  {
    NSLog(@"\n Object #%d is: %@\n", objectCount++, input);
 
    va_start(argList, input);
    while (currentObject = va_arg(argList, id))
      NSLog(@"\n Object #%d is: %@\n", objectCount++, currentObject);
    va_end(argList);
  }
}

This method will print out each argument using NSLog(). The assumption is made that the last argument will be nil. Here is how you might call the method, passing in two objects. What’s happening here is that I am sending getter messages, if you will, to the ‘ptr’ receiver. Each of these getters returns an object. Notice the nil value as the last parameter.

  [ptr printInstanceVars:[ptr str], [ptr date], nil];

Now, this example is a little contrived in that there is probably little value in passing in instance variables from an object, as I’ve done here. However, introducing more classes at this point may confuse more than help. If nothing else, hopefully you get the jist of how this works.

I haven’t come upon the case where this is necessary in an Objective-C application, however, when programming in C, this was quite handy when reading command line parameters. So,if you ever find the opportunity, now you’ll know how. And if you are into trivia, variable argument methods in Objective-C are referred to as variadic methods, go figure.

Many of the things that I’ve covered here are much better understood by looking at a real example. I’ve attached the Xcode project that I created to learn this stuff. You best bet is to download, open the project and mess around with the code.

Here is the main method of the example, so you can get an idea of how I tested each of the above examples.

int main(int argc, const char * argv[])
{
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  SomeClass *ptr = [[SomeClass alloc] init];
 
  // Simple message
  [ptr printInstanceVars];
 
  // Passing a single argument
  [ptr setStr:@"Testing"];
  [ptr setX:2008];
  [ptr printInstanceVars];
 
  // Nesting of messages
  [ptr setDate:[NSDate date]];
  [ptr printInstanceVars];
 
  // Passing multiple arguments
  [ptr setString:@"A new test..." andDate:[NSDate date] andInteger:99];
  [ptr printInstanceVars];
 
  // Passing variable number of argument
  [ptr printInstanceVars:[ptr str], [ptr date], nil]; 
 
  // This won't work...
//    [ptr printInstanceVars:[ptr str], [ptr date], [ptr x], nil];
  [ptr printInstanceVars:[ptr str], [ptr date], [NSNumber numberWithInt:[ptr x]], nil];
 
  [ptr release];
  [pool drain];
  return 0;
}

Download the Xcode Project
Download the Xcode project and take some time to tinker.

Once you’ve got a good handle on the overall application, look at line 27 above. Make any sense? Here’s the deal: the variable length method is expecting objects to be passed in. The code in line 26 will generate a runtime error given the message [ptr x] returns an integer (not an object). The way around this is to create an NSNumber object by sending a message to the NSNumber receiver, with the message ‘numberWithInt’ passing in as the parameter the integer returned from the getter message sent to the ‘ptr’ receiver. If all that makes sense, you’re well on your way :)

For completeness, the entire code listing and a screenshot are shown below:

// ===========================
// = SomeClass.h =
// ===========================
#import <Foundation/Foundation.h>
 
@interface SomeClass : NSObject
{
  NSString *str;
  NSDate *date;
  int x;
} 
 
// Getters
-(int) x;
-(NSString *) str;
-(NSDate *) date;
 
// Setters
-(void) setStr:(NSString *)input;
-(void) setDate:(NSDate *)input;
-(void) setX:(int)input;
-(void) setStr:(NSString *)str andDate:(NSDate *)date andInteger:(int)x;
 
// Other
-(void) printInstanceVars;
-(void) printInstanceVars:(id)input, ...;
-(void) dealloc; 
 
@end
#import "SomeClass.h"
#import <stdio.h>
 
// ================================
// = SomeClass.m =
// ================================
 
@implementation SomeClass
// =================
// = Getter methods =
// =================
-(int) x
{
  return x;
}
 
-(NSString *) str
{
  return str;
}
 
-(NSDate *) date
{
  return date;
}
 
// =================
// = Setter Methods =
// =================
-(void) setStr:(NSString *)foo
{
  [foo retain];
  [str release];
  str = foo;
}
 
-(void) setDate:(NSDate *)input
{
  [input retain];
  [date release];
  date = input;
}
 
-(void) setX:(int)input
{
  x = input;
}
 
-(void) setStr:(NSString *)strInput andDate:(NSDate *)dateInput andInteger:(int)xInput
{
  [self setStr:strInput];
  [self setDate:dateInput];
  [self setX:xInput];
}
 
// ================================
// = Print the instance vars =
// ================================
-(void) printInstanceVars
{
  // Use the getter method of the ’self’ object to print object instance variables
  //  NSLog(@"\n x: %d\n str: %@\n date: %@\n", [self x], [self str], [self date]);
 
  // The class can directly access the instance variables (versus calling message as above)
  NSLog(@"\n x: %d\n str: %@\n date: %@\n", x, str, date);
}
 
-(void) printInstanceVars:(id)input, ...
{
  id currentObject;
  va_list argList;
  int objectCount = 1;
 
  if (input)
  {
    NSLog(@"\n Object #%d is: %@\n", objectCount++, input);
 
    va_start(argList, input);
    while (currentObject = va_arg(argList, id))
      NSLog(@"\n Object #%d is: %@\n", objectCount++, currentObject);
    va_end(argList);
  }
}
 
// ====================================
// = Dealloc all object instance vars =
// ====================================
 
-(void) dealloc
{
  // No release needed of the integer instance variable ‘x’
  [str release];
  [date release];
  [super dealloc];
}
@end
// ===========================
// = Messaging.m =
// ===========================
#import <Foundation/Foundation.h>
#import "SomeClass.h"
 
int main(int argc, const char * argv[])
{
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  SomeClass *ptr = [[SomeClass alloc] init];
 
  // Simple message
  [ptr printInstanceVars];
 
  // Passing a single argument
  [ptr setStr:@"Testing"];
  [ptr setX:2008];
  [ptr printInstanceVars];
 
  // Nesting of messages
  [ptr setDate:[NSDate date]];
  [ptr printInstanceVars];
 
  // Passing multiple arguments
  [ptr setStr:@"A new test..." andDate:[NSDate date] andInteger:99];
  [ptr printInstanceVars];
 
  // Passing variable number of argument
  [ptr printInstanceVars:[ptr str], [ptr date], nil]; 
 
  // This won't work...
  //    [ptr printInstanceVars:[ptr str], [ptr date], [ptr x], nil];
  [ptr printInstanceVars:[ptr str], [ptr date], [NSNumber numberWithInt:[ptr x]], nil];
 
  [ptr release];
  [pool drain];
  return 0;
}

Jun 23, 2008

Objective-C: Defining a Class

Note: This post is the start of an on-going series for developers who are interested in learning to write applications for the iPhone. The entire series can be found here: iPhone Developer .

One of the first topics to cover when learning to develop native iPhone applications is how to code in Objective-C. Apple offers the Objective C Reference , a good resource, however, the best way to learn is by writing code. I took to Xcode to write a few simple examples, you’ll find the code below. At the end of this post I also include a link to download the Xcode project I was working with.

There are two aspects to a class, the interface and the implementation, both of which I recommend you store in separate files (although this is not a requirement).

The interface looks as follows:

@interface NameOfClass : NameOfSuperclass
{
  instance variables here...
}
class methods
instance methods
@end

The interface for my example:

// ===========================
// = Interface for SomeClass =
// ===========================
 
@interface SomeClass : NSObject
{
  NSString *str;
  NSDate *date;
  int x;
} 
 
// Getters
-(int) x;
-(NSString *) str;
-(NSDate *) date;
 
// Setters
-(void )setX:(int) input;
-(void) setStr:(NSString *)input;
-(void) setDate:(NSDate *)input;
 
// Other
-(void) printInstanceVars;
-(void) dealloc;
@end

A good coding practice is to save the implementation definition in a file with a name that matches the class name, with an extension of .h (for exampe: SomeClass.h).

This class is inherited from NSObject, the uber object. The class has three instance variables, two that point to other objects, one that references an integer variable. Take note of the getter methods: in Objective-C there is typically no ‘get’ in the front of the method name (in Java this might look like getX or getStr). Second, it should be obvious, that an instance variable can have the same name as a method, as it generally does with a getter. The ‘-’ in the front of the definition, signifies that the method is an instance method. We use a ‘+’ to define a class method (more on class methods in a future post).

One important thing to point out is the format used when declaring methods. For example, setStr() is defined as -(void)setStr: (NSString *) input ; This is translated to, the method setStr is an instance method (given the ‘-’) that returns a void type. The method takes one argument, that is a pointer to an NSString object, the name assigned to the parameter is ‘input’. The reason for the name will become more apparent when you see the implementation of the method below.

The format for the implementation of a class looks as follows:

@implementation NameOfClass : NameOfSuperclass
{
  instance variables here...
}
class methods
instance methods
@end

Here is how the implementation for the above class looks:

#import "SomeClass.h"
#import <stdio.h>
 
// ================================
// = Implementation for SomeClass =
// ================================
 
@implementation SomeClass
// =================
// = Getter methods =
// =================
- (int) x
{
  return x;
}
 
- (NSString *) str
{
  return str;
}
 
- (NSDate *) date
{
  return date;
}
 
// =================
// = Setter Methods =
// =================
- (void) setX:(int)input
{
  x = input;
}
 
- (void) setStr:(NSString *)input
{
  [input retain];
  [str release];
  str = input;
}
 
- (void) setDate:(NSDate *)input
{
  [input retain];
  [date release];
  date = input;
}
 
// ================================
// = Print the instance vars =
// ================================
 
-(void) printInstanceVars
{
  // Use the getter method of the 'self' object to print object instance variables
//  NSLog(@"\n x: %d\n str: %@\n date: %@\n", [self x], [self str], [self date]);
 
  // The class can directly access the instance variables (versus calling message as above)
  NSLog(@"\n x: %d\n str: %@\n date: %@\n", x, str, date);
}
 
// ====================================
// = Dealloc all object instance vars =
// ====================================
 
-(void) dealloc
{
  // No release needed of the integer instance variable 'x'
  [str release];
  [date release];
  [super dealloc];
}
@end

Other than learning the syntax of Objective-C, if you are familiar with OO development, most of this should be pretty clear.

A couple of things to point out:

  • The preferred file name for the implementation is the class name with a .m extension, in this example: SomeClass.m
  • Notice how this file imports “SomeClass.h” to read the class definition. If you are familiar with C, this is analgous to the #include directive. The benefit of #import is that the compiler will do the work for you to verify that the include file is only read once. If you’ve done any amount of coding in C, you’ll appreciate this convenience, if not, you won’t understand how nice a feature this is.
  • Within an instance method, all instance variables are within scope. For example, notice how the getter and setter methods refer to the instance variables.
  • Notice in printInstanceVars() method that there are two means to access the instance variables. You can use the ‘self’ object an send a message to the getter method (more on objects and messages in the next post), or you can directly access the instance variables.
  • If instance variables are pointers to objects, as are ‘str’ and ‘date’, it’s your responsibility as the developer to free the memory for those objects. The dealloc method is where you do this work. More on that to come…

To complete the example, the code that follows declares an instance of the SomeClass object, and uses the setter/getter methods to print the instance variables to the console.

#import <Foundation/Foundation.h>
#import "SomeClass.h"
 
int main(int argc, const char * argv[])
{
  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  SomeClass *ptr = [[SomeClass alloc] init];
 
  [ptr setX:99];
  [ptr printInstanceVars];
 
  [ptr setStr:@"Testing"];
  [ptr printInstanceVars];
 
  [ptr setDate:[NSDate date]];
  [ptr printInstanceVars];
 
  [ptr release];
  [pool drain];
  return 0;
 
}

A few comments on the above code:

  • Notice this file imports the SomeClass.h interface file.
  • Like working with C, main() is the function that gets everything started.
  • ‘ptr’ is a reference to an object of the SomeClass class.
  • Calling instance methods of an object follows this form: [object message:parameters]

A screenshot of the output from within Xcode of this example is below:

Creating Classes

I recommend you download the Xcode project and give it a go.

Let’s go with that for today. In the next post I’ll talk further about this simple example, including instantiation of classes, sending messages to methods and freeing memory of the instance variables.

Jun 20, 2008

Road to iPhone: Intro

Having spent the past 8 years working with mobile application development (beginning with the book Core J2ME that I wrote in 2000), it’s odd that its taken me so long to dive into developing for the iPhone. The good news is, I’m now fully engaged and plan to spend a fair amount of time writing about this new endeavor…

This is the first in what I anticipate to be a long series of posts as I ramp up on all things iPhone. The intention is to share how I am going about learning to develop iPhone applications, in the hopes it can help you.

To begin, my plan is to learn the following, in the order shown below (with Xcode, Apple’s development environment, thrown in as needed):

  • Objective-C
  • Cocoa
  • iPhone SDK (API’s)

So let me begin by pointing you to a few resources:

As you’ll see once you download a few of the docs, there is huge amount of information here. To keep things in perspective, my intention is not to revisit all the material in the documents, as much as point out the nuances that I think will be important in becoming a proficient iPhone developer.

A good example is the next post in this series where I’ll point out how to work around one of the sore spots for many who come to Objective-C from an object-oriented language, lack of support for private methods. With Objective-C there are a few tricks to "hide" methods, however, it’s really just a slight-of-hand, so to speak. I’ll explain more later.

There is a fair amount of information to digest above (assuming you are new to Objective-C, Cocoa and/or Xcode). Once you are ready for more, here is a list of additional documents to further immerse yourself:

I hope you’ll join me as learn the ropes for developing iPhone applications.

Jun 12, 2008

Mobile Developer Survey, $1000 Drawing

I was contacted by VisionMobile, a market analysis and strategic advisory firm in the wireless sector, to pass along a link to their most recent survey for developers who are building mobile applications.

Although this is not a Mac tip or trick, I know there is a great deal of application development done on a Mac for a range of mobile devices and platforms. Also, seeing as all developers who complete the survey will be entered into a drawing to win an Amazon voucher worth $1000, I thought you might be interested :)

The survey consists of 5 pages of questions, somewhere around 10-15 minutes of your time. The deadline to complete the survey is Friday, June 27th. The winner will be announced on Friday, July 4th.

If you are working with mobile devices, give it a go, your insight might be helpful to someone else down the road…

Jun 11, 2008

iPhone SDK, First Impressions

I’ve been spending some time with the iPhone SDK to get a perspective on the architecture, tools and overall landscape. In addition, I’ve started to develop a few applications with Xcode (Cocoa/Objective-C) to exercise the tools for building iPhone applications. More on application development next week…

So far, I’m impressed. Here’s how I see things…

The Platform:
The iPhone architecture consists of the Core OS (kernel level resources), Core Services (system services), Media (audio, video and graphics) and Cocoa Touch (classes for managing graphics and event-driven applications).

From my perspective, there are two key areas that are exposed. First, the system services in Core OS, accessible through a C library (LibSystem) where one can work with wrappers for low-level features such as threading, networking, file system, Bonjour, among others.

Second, and even more compelling from a user interaction perspective, is the Media layer. Quartz is a 2-D drawing engine. Through the C-based API one can work with vector graphics, lines and shapes, etc. Core Animation is an Objective-C API providing animation and is also part-and-parcel to providing dynamic feedback from the UI. Many of the standard animations that make the iPhone so compelling (screens sliding, flipping over, etc) are included in View classes in the UIKit. OpenGL ES is a mobile version of the OpenGL standard and is the engine behind 3-D graphics. When high-frame rates are in order (think games), OpenGL is the answer.

From what I can tell, the iPhone SDK looks quite comprehensive, providing access across all areas of the device.

Distribution:
One of the challenges since day one for mobile developers has been getting their applications in front of potential users. With the iPhone, applications will be available through Apple’s App Store, which is accessible on the phone as well as through a desktop/laptop system. My understanding is that Apple will offer developers 70% of the revenue. Not unreasonable given Apple will provide the store front and manage all that goes with it.

Overall, an impressive start to what I think could be a significant, and welcome change, to the mobile development landscape.