A little trick

July 8th, 2010

Most subclasses add instance variables. Objects initialized using initializer methods inherited from superclasses will only be partially initialized. Therefore you should override all initializers to avoid accidentally creating a partially initialized object. However unless there is a reasonable default for all instance variables this may not be possible. In such cases, one usually overrides the initializer by a method returning nil. However it is difficult to debug nil-errors. A better solution is to override the method to invoke doesNotRecognizeSelector: Since _cmd is always the current method’s selector one can use the same method body. For instance:


- (id) init
{ [self doesNotRecognizeSelector:_cmd]; return nil; }

Ragdoll Blaster 2

March 2nd, 2010

Ragdoll Blaster 2 was released yesterday. It contains some of my code: a number of months ago, my friends at Backflip Studios asked me to optimize the game’s physics engine (ODE), providing free cycles for better graphics, sounds and levels. Of course the main question is … is it fun? I think so!


An amusing factoid: the game screens are rendered by OpenGL, but the rest of the UI is heavily customized Cocoa UI widgets. You can really make UITable look different!

www.stepwise.com gone

December 1st, 2009

Unfortunately Scott Anguish has deleted stepwise, a very good Cocoa development website he ran. He explains his reasons here. As is often the case, Web Archive has only archived the first page — not very useful.

This is precisely why I wrote Find It! Keep It! — to keep the articles I like. I just need to find the time to fix it so that it works on the new WebKit and Snow Leopard — If only days were 48 hours long!

What to do if XCode won’t add a source code file to a Project

November 30th, 2009

Sometimes XCode won’t let you add a source code file to a project when you click “Add, Existing Files…” from the “Groups & Files” context menu: you find that the filename is greyed out and cannot be selected.

To work around this, you can drag the file from the Finder to the “Groups & Files” pane.

Woohoo!

October 23rd, 2009

I just received the author copies of my book.

Teach yourself Cocoa Touch Programming in 24 hours

October 19th, 2009

A few months ago, Pearson Education contacted me about writing a book about Cocoa Touch. I agreed because although I had a lot of experience on other platforms, I found Cocoa somewhat bewildering when I first encountered it. Most books either assumed a Mac background or really wanted to teach me Object-Oriented programming from the ground up. Often after reading one of them, I had the impression I had learnt something until I tried to apply whatever it was I learned: The problem was that they glossed over how Cocoa really works, and why it was architected in that way.

Cocoa and Objective-C are very powerful tools to build Applications and Graphical Interfaces quickly. This power comes from splitting GUI tasks into a few well-chosen abstractions that reduce the amount of code we have to write. Once understood, these abstractions seem obvious, so most books simply introduce them as the way things are done in Cocoa, leaving beginners bewildered.

Instead I show readers how these abstractions work and how they simplify their code. Because they understand the mechanics of each task, readers will be able to resolve most difficulties on their own quickly, rather than exploring new levels of frustration. To further help, the book is interlaced with debugging techniques. My goal in writing the book was to provide a sound foundation that programmers can use to build functional applications, and feel confident that they can solve the problems they will encounter. Instead of covering the latest API fashions, I concentrate on the APIs and tools you’ll actually use and will need to understand.

The book was published last Thursday, Oct 15 2009, and is available now at the publisher’s. Amazon shows they have yet to receive it (and therefore discount it). It’s in full color!

Understanding the Objective-C Language

In the first five chapters, you’ll build a basic application: a Calculator. You’ll learn how to use the key tools used when developing iPhone applications: Xcode, the debugger and Interface Builder. It also teaches you Objective-C: Objective-C is a thin layer on top of C which adds language support for object-oriented programming. Cocoa uses reference counting for memory management, but the judicious use of auto release pools makes this much easier than you might expect. You’ll also learn about Cocoa Touch’s Foundation classes with provide basic functionality such as Unicode strings, arrays, dictionaries. Practically speaking, by the end of chapter 4 you’ll have written a functioning calculator.

When I first learned Objective-C, I found many bugs intractable because I did not understanding messaging. To help you avoid this pitfall, I explain messaging and how it is implemented in chapter 4. Similarly, it took a while for me to understand auto release pools. They simplify your code, but are often presented as a form of magic you just use. My book is a magic-free zone, clarifying how they work and their limitations up-front. Other Objective-C particularities you’ll learn about are class objects, updating classes on the fly, class clusters, key-value coding and key-value observing. By the end of chapter 5, for most intents and purposes you’ll be an Objective-C expert. Unlike competing books, and Apple’s own documentation, I detail the computational complexity of Objective-C arrays and dictionaries.

User Interface Foundations

The building blocks of user interfaces are views. To build a user interface from views, one simply builds a tree of views (a view hierarchy) which specifies the location and order in which views are drawn. Most interfaces can be built using Interface Builder, a graphical design tool. Unlike competing solutions, Interface Builder does not generate code, but a NIB file that states how to build the view hierarchy. Most books only cover building user interfaces in Interface Builder. As a programmer this left me with a bad taste, as I was relying on some unknown mechanism working behind my back. Debugging was difficult because I had no idea how NIB files were loaded. Instead I show you how to build view hierarchies in code, how NIB files are loaded, and the pitfalls you may encounter.

Views draw themselves using a 2D renderer called Core Graphics (or Quartz). They respond to user interaction dispatched to them by Cocoa. Implementing your own User Interface element (a button) will give you a clear understanding of the ins and outs of user interface elements, and will help you polish your applications with custom user interface elements.

Unlike most user-interface solutions, Cocoa is not architected as a library. That is to say, your application does not just call library functions at will. Cocoa is architected as a framework: it calls your application code when it needs to. This turns out to be a powerful solution, but is disconcerting for programmers coming from other platforms. Because misunderstanding the run loop causes seemingly unrelated bugs I spend entire chapter discussing how run loop is used and how it interacts with other Cocoa sub-systems such as the auto release pool, and the responder chain.

A distinguishing feature of the iPhone’s user interface is how much animation it uses. These animations are created with Core Animation. Core Animation uses the iPhone’s 3D graphics chip and a separate thread to create smooth animations. Understanding Core Animation’s architecture will help you use it and remember its limitations. To further help you I share tips learned developing commercial software. By the end of this chapter, you’ll have implemented your own Cover Flow clone shown above! (animal images courtesy of http://www.public-domain-image.com).

Advanced User-Interface Elements

View Controllers reduce the amount of code you must write. Unlike many beginning programmers, you will not confuse them with views because the book clearly differentiates them. An example will solidify your understanding: displaying a Scientific Mode in the calculator when the iPod is rotated.

Tables are an essential component of most user interfaces. The iPhone’s table support is particularly flexible, and I’ll show you how you can customize it to create fast scrolling distinctive tables. In this hour, you’ll build a table based application that lazily loads data from an Internet source: a Twitter application.

Many applications present information on multiple screens. Navigation bars and Tab bars provide a standard way of navigating between the screens. I show you how to build applications using these user interface elements, and show you how the views and view controllers interact.

iPhone OS 3.0 introduces undo/redo functionality. Cocoa Touch solves this problem in a particularly elegant manner. However, it differs substantially from other solutions you may have used. To help you understand it fully, I dedicate an entire chapter to understanding the problems it solves, how it works, and why it was architected in this way.

Accessing the Internet

By providing full internet connectivity and the ability to render most web pages, the iPhone enables whole new classes of applications. To help you build robust applications, chapter 14 discusses how networks work in detail. Working through a real example (adding error handling to the Twitter application) shows you how this is done in practice.

Chapter 15 introduces UIWebView, a versatile User Interface component able to render documents in HTML, PDF, RTF, RTFD, Microsoft Office or iWork formats. You’ll learn how to use Javascript to update HTML formatted pages or parse JSON strings, and how to use new HTML5 features supported by the iPhone.

Saving and Retrieving Data

Cocoa Touch provides four means of saving and retrieving data: application preferences, files, a small sql database, and Core Data. You’ll learn how to add application preferences to the Twitter application, that users can customize in the Settings application. In chapter 17, I discuss when and how to use files or the sqlite database. iPhone OS 3.0 added Core Data which lets you load and save objects to storage transparently by providing a single object definition instead of writing your own classes and your own serialization code. To help you decide whether or not to use Core Data, I discuss its performance characteristics.

Interacting with the World

Only a few years ago, the idea of a tiny device containing your music and video library, finding your location anywhere on the planet, and using accelerometers as a user interface would have seemed like Science Fiction. The iPhone is a remarkable convergence device. Chapters 19 and 20 explains how to use these capabilities in detail.

Chapter 21 shows you how to share data with other applications. Custom URLs let you start other applications. Pasteboards provide cross-application copy and paste functionality. To export data from your device, I show you how to send emails from your application, or run a tiny webserver.

Completing Your Application

Completing your application involves four tasks: debugging it, optimizing it, localizing it and shipping it.

I devote an entire chapter to debugging, showing you not only how to use the debugger gdb, but also dtrace, valgrind, and nib2obj. Sometimes however, bugs are caused by misunderstanding how the frameworks work. Usually other programmers can help you, but sometimes the only solution is to reverse engineer the framework. To help you do this, the chapter ends with a short tutorial teaching you how to do this.

Optimizing your application is another key topic and has its own chapter. You’ll learn how to write your own profiling code, and learn how to use the two iPhone profilers: Shark and Instruments. Because of the iPhone’s memory limitations, it is particularly important to minimize your application’s memory consumption. To further help you, I introduce the Clang static analysis tool which helps you detect memory leaks at compilation time.

The final chapter covers localization and shipping your application. Because the App Store is the only authorized means of distributing applications, and because Apple can reject your application once you submit it for publication, developing for the iPhone is somewhat risky. To help you mitigate this risk, I analyze the types of applications Apple has refused to distribute on the AppStore, and provide some simple guidelines to follow.

Additional materials

If you haven’t programmed C in a while, I provide Appendix A to quickly refresh your memory of the salient points.

While developing for the iPhone you may encounter a number of issues due to Apple’s development tools. To help you resolve these issues quickly, Appendix B devotes 18 pages to debugging these issues.

Appendix C lists resources I have found useful when developing iPhone applications.

Appendix D includes a number of advanced topics of interest to expert programmers: how Cocoa starts your application, a deeper discussion of exceptions, and how and when to use threads.

Safari 4.0 incompatible with Find It! Keep It!

June 8th, 2009

Just a quick note to mention that Find It! Keep It! is not compatible with Safari 4.0. When you install Safari 4.0, it updates WebKit in a manner that breaks Find It! Keep It!. I will fix this but given my current workload, it may take me a few months.

Article published in Mac Tech

June 6th, 2009

Mac Tech just published my article on call stack logging which lets you see which function calls led to my NSLog replacement being invoked. The nice thing is that it works for C, C++ and Objective-C unlike most of the solutions you see elsewhere. The source code should show up on their ftp site some time soon. With few developer magazines surviving (Dr Dobbs webified, BYTE gone), I’m glad Mac developers still have a print magazine to read.

Tetratile update

February 7th, 2009

When you replay a game, I’ve added a panel to let you single step through the moves you made, so that you can better learn how the game works.

I just submitted this update to Apple for inclusion in the AppStore.

Fast enumeration on 10.4

January 29th, 2009

Tomorrow I’m showing some software I wrote to a client, and I don’t want to lug the external Harddrive on which Leopard is installed with me. The laptop still runs 10.4 for testing Find It! Keep It!

The software uses fast enumeration on arrays and sets. Building with the Mac OS 10.5 SDK and with 10.4 as deployment target worked, but running the code on 10.4 failed. The method countByEnumeratingWithState:objects:count: was missing. So I thought I’d add it — I stole its implementation from Cocotron, and added conditional posing for 10.4 systems:


// Stolen from Cocotron

#import <AppKit/AppKit.h>

@interface NSArrayEX : NSArray
@end


@implementation NSArrayEX

+ (void) load
{
  NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

  OSErr err;
  SInt32 systemVersion;
  if ((err = Gestalt(gestaltSystemVersion, &systemVersion)) == noErr)
    if ((systemVersion & 0xfff0) == 0×1040)
      [self poseAsClass:[NSArray class]];

  [pool release];
}


-(NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)length;
{
  int numObjects=MIN([self count] - state->extra[0], length);
  int i=state->extra[0];
  int j=0;
  state->itemsPtr=stackbuf;

  for(j=0; j<numObjects; j++, i++)
    state->itemsPtr[j]=[self objectAtIndex:i];

  state->extra[0]+=numObjects;

  state->mutationsPtr=(unsigned long *)self;

  return numObjects;
}

@end




@interface NSSetEX : NSSet
@end


@implementation NSSetEX

+ (void) load
{
  NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

  OSErr err;
  SInt32 systemVersion;
  if ((err = Gestalt(gestaltSystemVersion, &systemVersion)) == noErr)
    if ((systemVersion & 0xfff0) == 0×1040)
      [self poseAsClass:[NSSet class]];

  [pool release];
}



-(NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)length;
{
  int i;
  state->itemsPtr=stackbuf;
  
  state->mutationsPtr=(unsigned long*)self;
  if(!state->state)
    state->state=(unsigned long)[self objectEnumerator];

  id en=(id)state->state;
  
  for(i=0; i<length; i++)
  {
    state->itemsPtr[i]=[en nextObject];
    if(!state->itemsPtr[i])
      return i;
  }

  return i;
  
}

@end

It works surprisingly well. Unfortunately I then discovered that you can only create a 16 bit grey image context on 10.5 Oh well.

(Sorry for the horrible layout — I don’t have the time to dink with Wordpress right now)