iPhone

If you’ve found a need to work with JSON (including with the iPhone), I want to point you to an excellent Google code project: http://code.google.com/p/json-framework/. The author of this framework can be found here.

This framework implements a strict JSON parser and generator in Objective-C. It’s easy to work with and can be used across any number of projects with ease.
Read more »

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 .

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.

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.

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.

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.

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.

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.

Apple has announced their World Wide Developer Conference (WWDC), which will take place in San Francisco on June 9 – 13th. For all those who’ve been chomping at the bit to learn more about the iPhone, this should be a great opportunity to be immersed in technology, tools and toys!

Read more »