Objective-C

Dustin Bachrach:

OCUDL is an experiment to bring user defined literals to Objective-C. A literal is a shorthand expression that creates a value of a certain type. For example, 25ul creates an unsigned long of 25, and @”hello” creates an NSString of hello. User defined literals bring this brevity and expressivity to our own types.

Dustin has a post that is well worth reading that describes the details of OCUDL.

Below are two macros I paste into most every project. Besides saving a few keystrokes, they work well when using the color picker application. Let’s look at the macros first:

#define RGB(r, g, b) 
    [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]
#define RGBA(r, g, b, a) 
    [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:a]

Here’s the code without/with the macro:
Read more »

Okay, so figuring out how to unwind an Objective-C object into its base representation goes against all that is object-oriented programming, however, it’s interesting none-the-less.

In Objective-C there is a directive, @defs(), that outputs (at compile time) the list of instance variables for a class. We can use this list to create a C structure with the variables of a specified class.
Read more »

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.

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.

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.

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.

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.