December 15, 2009

MapKit Span Doubling Bug

I am currently working on an application that uses the new MapKit API in OS 3.0. Although the feature set is a bit sparse, I have found it useful. I look forward to future added features to this neat package.

There is one nagging bug, though: sometimes setting the map to a region will end up zoomed out too far. What appears to be happening, and has been confirmed by others in this thread over at stackoverflow, is that the span values are essentially doubled. A doubled span means a greater area is viewed, equating to a zoomed out view.

This bug didn't happen all the time, but recently it now happens to me ALL the time on the simulator. Others say the bug persists on the actual device as well.

Until Apple fixes this bug, I needed to provide a fix to get around this annoying defect. The error seems to be introduced when assigning the region to the map:

[self.mapView setRegion:myRegion animated:YES];


The hack is to look at the map region after making the assignment. If the span does not equal what you set it to, then divide the original span values by 2.0 and try it again. Since the MapKit code is doubling the values, we will halve the values beforehand to get to the value we want. Idiotic hack, for sure, but gets the job done:

[self.mapView setRegion:myRegion animated:YES];

// did the span get screwed up?
if(self.mapView.region.span.latitudeDelta != myRegion.span.latitudeDelta ) {
    NSLog(@"Span got doubled, adjusting");


    // hack to fix span doubling bug
    MKCoordinateRegion temp = MKCoordinateRegionMake(myRegion.center
            MKCoordinateSpanMake(myRegion.span.latitudeDelta/2.0,
                                             myRegion.span.longitudeDelta/2.0));
    [self.mapView setRegion:temp animated:YES];
}

The nice thing about this hack is that it only takes affect if the bug appears. Should you forget about this hack and Apple has long since fixed the problem, the hack is harmless.

October 31, 2009

A Truly Modal UIAlertView

I don't know why it took me so long to realize this, but UIAlertViews are not modal. Yes, they are modal as far as the UI is concerned, but your code continues running after you call the show method.
I discovered this while making a callback in my TableFormEditor package. In the callback, the form is asking the delegate "is it ok to save this data?". My delegate takes a quick look, sees something wrong, and fires up a UIAlertView to get the users input if it is ok or not. However, the [alert show] call came back immediately and the form was given a bogus answer, while the dialog was still waiting for user input. Dang.
After a bit of research, it seems that Mac UI frameworks do not embrace the concept of pure modal dialogs. I've read both sides of the argument, but it really shouldn't be an argument at all. You *should* design your code to not rely on modal behavior and instead make use of the delegate concept, but you *should* also have the ability to do modal if your code warrants it.
Sure, I could rewrite my code to move the logic from the location it belongs over to the delegate, but this creates an unmaintainable mess in my code. This is one case where a modal would really keep things neat and tidy. To address this in a general way, I created a wrapper class around UIAlertView that shows a modal dialog. The class is called JESAlert. The show method will not return until the user selects a button, and it will return the selected button index.
- (int) show;
To simplify things, this class does not allow a delegate, so the init method is similar to the original UIAlertView init but without the delegate parameter.
- (id) initWithTitle:(NSString*) title
             message:(NSString*) message
   cancelButtonTitle:(NSString*) cancelButtonTitle
   otherButtonTitles:(NSString*) otherButtonTitles, ...;

Simply call this init, then call the show method. What it returns is the selected button index.
I also enhanced the UIAlertView interface to allow for an array of otherButtonTitles, instead of just the varargs that is currently supported. I needed this feature once upon a time, so I added it.
- (id) initWithTitle:(NSString*) title
             message:(NSString*) message
   cancelButtonTitle:(NSString*) cancelButtonTitle
otherButtonTitleArray:(NSArray*) otherButtonTitles;
And lastly, since I am on a JESON kick, I have created a JESON-aware interface. You can define your UIAlertView properties in a JESON file and deploy that as a resource with your application. This removes the typical static text settings from your code and moves it into a JESON file.
To use it this way, simply use the plain init method (or combine alloc and init with a new), and call the showWithJeson: method. The filename is expected to be a resource bundle stored in your application. This will also return the button index.
JESAlert* alert = [JESAlert new];
int button = [alert showWithFile:@"alert.jes"];
The JESON file contents look like this:
alert {
    title = "Your alert title" 
    message = "More details of your message" 
    cancelButtonTitle = "cancel button title or null"
    otherButtonTitles = ["button 1", "button 2"]
}

The JESON portion of JESAlert is a bit more feature rich than the init approach. You can also run the normal, non-modal version of UIAlertView, but build the properties in a JESON file. Just add the modal = false property. You can also specify a delegate by setting the delegate property.
For example, the old-fashioned way:
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"An error"
  message:@"Something really bad happened"
  delegate:self
cancelButtonTitle:@"Stop doing it"
otherButtonTitles:@"try again", @"try harder", nil];

[alert show];
And here is how it could be set up in a JESON file:
alert {
    title = "An error" 
    message = "Something really bad happened" 
    cancelButtonTitle = "Stop doing it"
    otherButtonTitles = ["try again", "try harder"]
    delegate = self
    modal = false
}
And accessed in the code like this:
JESAlert* alert = [JESAlert new];
alert.jesonContext = self;
[alert showWithFile:@"jeson_alert.jes"];
The jesonContext property is needed to handle variable references in your JESON text, like the "self" used above on the delegate property.
The JESON support can be easily disabled if you are not so inclined, as it requires the JESON library available here. To disable JESON support, simply comment out the define at the top of the JESAlert.h file.
//#define USE_JESON
I have not yet taken the time to create an Xcode project for this, so for now I offer this class as a .h/.m pair of files. The code is available on the Osmorphis group: JESAlert-1.0.zip.

October 13, 2009

Variable References in JESON

JESON
This is a continuation of my series on JESON, an enhanced replacement for JSON. The previous articles were:
  1. An introduction to JESON
  2. A quick overview of where to get JESON and how to use it
In this part I describe an additional enhancement to JESON. I have been developing and redefining JESON as I go along, so a few things have changed and will continue to change as this specification evolves. These changes, of course, drift farther and farther away from the original JSON syntax, but all for the better. The following enhancement is variable support in values. In JSON and JESON, you can assign constant values to keys:
x = 23
y = 'hello'
z = [1, 2, 3]

and so on. But now in JESON, you can assign a variable to a key. This is done by simply giving the name of the variable:
x = 23
y = x
This will assign 23 to y. You can also use variable references in array elements:
x = 23
y = x
z = [x, y]
Basically, anywhere a value is allowed (in dictionary key assignments and elements of an array), a variable reference can be used.

Valid key/variable names

In order for this to work, your variables and dictionary keys cannot look like a constant, meaning:
  • names cannot be true or false or null or start with a number
  • names cannot have spaces in them
Variable/key names can be alpha-numerics (a-z, A-Z, 0-9), but can also include "." and "_". The need for "." will be apparent later. Note that the old JSON key name rules can still be applied, like putting spaces or weird character in key names. But if you do, you cannot reference that key in a value. For example, you can still do the first line, but there is no way to do the second line:
"my key" = true
x = my key // syntax error

Name scoping

Variables have scope, just like in any programming language. Each nested dictionary forms a context. When trying to resolve a variable, JESON will search upwards through the nested dictionaries. In the following example, x will be assigned 72 because that is the nearest scope for y:
outer {
    y = 23
    inner {
        y = 72
        x = y
    }
}
If you comment out the inner y, then x is assigned 23. JESON will continue up the nested contexts until it finds it. If it doesn't, it uses null for the value.

Exposing Host Scope

Scope is not limited to the JESON file itself; context searches can spill out into your host application. In the above example, if there are no y's at any level, then JESON can ask the host application for the variable. To support this, the host application needs to set the hostContext property on the JESON parser object. The value to this property is an object that supports Key-Value coding. You could use self, or even construct a context via JESON, as in this example:

// create a parser object
JESON* parser = [JESON new];

// create a dictionary 
id context = [parser parseString:@"y='hello'"];

// set that dictionary as our external context
parser.hostContext = context;

// and parse something that references a variable
id root = [parser parseString:@"x = y"];
This code will assign to root a dictionary with the key "x" set to the value "hello". The extension to the NSString class has also been extended to support this:
NSString* jeson = @"x = y";
id root = [jeson parseAsJESON:jeson usingContext:context];

The beauty of this is a host application can provide himself as the context, and then the JESON has access to all its properties.
// set some properties
self.myProperty = somevalue;
self.anotherProperty = anothervalue;

// parse some JESON
parser.hostContext = self;
id root = [parser parseString:@"x = myProperty, y = anotherProperty"];
As a practical application of this technique, I am using the new TableFormEditor which can have the form described in JESON. I want to edit a form that can have a title that varies depending on the situation. The host application determines the title and puts it in a property for the JESON to reference:
if(editing) {
    self.formTitle = @"Edit data";
} else {
    self.formTitle = @"Add data";
}



id root = [parser parseString:myJESON];
And the JESON text could have something like this:
showLabels = true
title = formTitle

Variable Paths

To be consistent with Key/Value Coding, the variable name can also be a path in order to traverse nested contexts and to dig into dictionaries:
globals {
    y = "Hi"
}

outer {
    y = 23
    inner {
        y = 72
        x = globals.y
    }
}
Instead of using one of the "local" y values, we pull y out of a different dictionary. You can use this syntax to dive into any dictionary:
stats {
    records {
        years {
            y2008 {
                july { income = 5, expenses = 3 }
                august {
                    income = 4
                    // expenses are the same as in July
                    expenses = july.expenses
                }
            }
        }
    }
}

income = stats.records.years.y2008.august.income

Note that the path is relative to where the reference is. JESON will still search up through the nested contexts, but instead of looking for a single key, it is looking for a path. This variable "path" is also supported when accessing host application data.
There is one caveat to what is supported, due to the way the nested dictionaries are parsed. You cannot reference a dictionary by name if you are a descendent of it. For example, the key "expenses" above could not reference "y2008.july.expenses" because expenses is a grandchild of y2008. This limitation is because the y2008 dictionary has not been created fully yet, as it is recursively getting built. In most cases, this is not a problem, as the contexts are searched upwards through the ancestors, so there is little reason to name your ancestor. Many people don't realize that key/value coding also works with arrays. But the key is not applied directly to the array. Instead it is applied to every element in the array and returns an array of those results. For example:
fields [
    { id = 1 }
    { id = 2 }
    { id = 55 }
]

ids = fields.id
// ids => [1, 2, 55]
An updated JESON parser has been made available with the features described here. Get it off the Osmorphis group: jeson.zip.

October 8, 2009

kaLua

For years I have been searching for the "perfect" scripting language. I started with Unix shells and Tcl, migrated to Python, toyed with Javascript and Groovy, and lately I have ventured into the world of Lua. To me Javascript is one of the more elegant syntaxes. It is fairly simple with a good balance of words vs. puctuation. However, Javascript is designed for web pages and the various runtimes that are available are rather large and cumbersome. Lua's size is extremely attractive, and I like Lua's simple syntax and no-nonsense approach.
But I felt the language is too wordy. This is one of the turnoffs Ruby has as well. There is a good balance that can be reached between wordy, verbose languages (like Objective-C) and terse, cryptic languages (like Unix shell). I am constantly looking for that balance. Python is close, but I really dislike the "blocking via indent", even after programming in it for years; it never found a place in my heart.
So what's wrong with Lua? Not much, really, as long as you're not looking for a true OO language. But it's not perfect. For starters, Lua denotes blocks via do/end, function/end, and if/then/end keywords. To me, this makes the code too wordy. The density of words over punctuation is too great. I wanted to shift that balance, plus make the syntax a little closer to existing languages. There are some other constructs in Lua that strike me as odd or "old-fashioned". For example, the [[/]] pair to create multiline strings. I find the Python/Groovy approach of using triple quotes (""" or ''') much more appealing.
So I looked at the Lua parser code and it seemed simple enough. I started tweaking and adding things. Before I knew it, I had changed a great deal of the syntax.
Once I realized I had a new language on my hands, I needed a name. I have come up with "kaLua", which could stand for "Kick Ass" Lua, but it really is just the best I could come up with and still retain the "Lua". I'm all for changing this name. One alternative that stands out is Superscript.
kaLua is a derivative of Lua and is still very much Lua-like. It would be nice if it did not change existing syntax and merely added to it, but some things had to change. I'll describe these incompatible changes below. This document summarizes those changes made to Lua to create the kaLua almost-superset. Mind you, these changes come from a syntax snob, and many will dislike these changes. Syntax is a matter of taste; this is my taste. If it's not yours, then move along. I won't be offended.

Function Blocking

Functions can be declared like this in Lua:
function hello() print('hello world') end
and they can be declared anonymously (inline) like this:
if something then return function () print('hi') end end
kaLua adds curly brace blocking to function definitions. The above two could be written as:
function hello() { print('hello world') }
and
if something { return function () { print('hi') } }
It does not matter what line the {} characters are on; Lua is fairly insensitive to line breaks as opposed to some scripting languages.

If/then/elseif/else Blocking

Blocking for the if/... set of statements is a bit more complex, mainly because the current Lua syntax is somewhat inconsistent. You can have numerous "then" portions but only one "end":
if something then do_something() elseif something_else then do_another_thing() elseif something_else_yet then do_that_again() else last_ditch_effort() end
The blocks for each condition are separate contexts. To make this cleaner and clearer, kaLua adds support for braces and removes the useless "then" keyword:
if something { do_something() } elseif something_else { do_another_thing() } elseif something_else_yet { do_that_again() } else { last_ditch_effort() }
The braces do not have to appear on the same line or on a different line. Although you can continue to use the old style blocking, you have to be consistent within one if compound statement. In other words, you can't use braces in the if block and use the old style blocking in the else portion.

While Blocking

The while loop blocks via a do/end pair:
while something_is_true do something() end
kaLua adds an addition to support braces:
while something_is_true { something() }

Repeat/Until Blocking

Lua creates yet another form of blocking with the repeat/until pair:
x = 3 repeat print('repeat') x = x - 1 until x == 0
kaLua simply adds braces to form the block for consistency. The block creates a new context, and the condition in the until clause does have visibility to that context, even though it is physically outside the block.
x = 3 repeat { print('repeat') x = x - 1 } until x == 0

Standalone Blocks

Lua uses do/end blocks to create a nested context:
x = 'hello' do local x = 23 end
kaLua replaces the do/end pair with {}:
x = 'hello' { local x = 23 }

Function Calls

Lua supports 3 different syntaxes for making function calls:
x = callme("23") x = callme{f="23"} x = callme"23"
Of these, only the first one makes sense. The other two muddle up the language syntax and offer little advantage. I guess they are syntactic sugar, but they don't seem very "sweet" to me. The second two examples above are no longer supported. Only the following is allowed:
x = callme("23")
Because of the additional support for braces in the syntax, the second one conflicts with the updated grammar. The third function call form is just loopy; I hope no one really uses that.
If you need to pass a table as an argument, surround with parens like you would expect. In other words, function calls always involve parens. To me this is consistent and clean:
x = callme({f="23"})

Multiline Strings

Lua supports multiline strings with the [[/]] pair, and also supports nested multiline strings with [=[/]=], [==[/]==], etc pairs:
print([[this is a multiline string]]) print([=[ this is a [==[nested string]==] so there you have it]=])
The use of [[/]] is pretty ugly and uses the bracket characters where they would be best used for indexing. kaLua changes the multiline string to use the triple quote concept from Python and other languages:
print("""this is a multiline string""") print('''this is also a multi- line string''')
kaLua gets rid of the nested string format altogether. Its value is very dubious and it is extremely ugly. For an embedded language that prides itself on simplicity, this feature seems unnecessary.

Comments

Lua uses the -- characters to denote a single line comment, and --[[/]] for multiline comments:
-- this is a comment --[[ print("this code is commented out") ]]
kaLua changes these to more common comment sequences:
// this is a comment /* print("this code is commented out") */

Operators

Lua uses ~= for "not equals". kaLua adds a more common operator sequence !=

Summary

That sums up the additions and changes made to the Lua syntax. I have these changes implemented in a version of the library. I really haven't used it much and the code needs some more tweaking. I would like to make kaLua be a true superset of Lua and put back some of the things I removed. The only thing kaLua cannot support is the function call syntax that uses curly braces instead of parens. This is one feature of Lua that won't survive in kaLua.
There are a few other quirks of Lua I don't like, but will require a lot more thought and code mangling. The biggest offender to me is the "method call" syntax:
object:method(parms)
It's really not that bad, but I find it a little hokey. How else to do it? No idea. This is still better than:
object.method(object, parms)
It would be preferable that I can call it with a dot instead of the colon and have it just figure it out, and pass object as the self parameter:
object.method(parms)
If anyone is interested in getting a copy of kaLua, let me know via a comment or an email. If there is enough demand (which I don't expect), then I can post the code.

September 23, 2009

Using JESON

JESON
In part 1 of this series, I introduced JESON, a superset of JSON that adds various syntax enhancements. Some may be appalled that I would dare change JSON, but I based my decision on several factors:
  1. JSON's compliance with JavaScript syntax is becoming less an advantage because of the dangers of blindly evaluating JSON source,
  2. I don't use JavaScript, so I could care less about maintaining compatibility with it, and
  3. Since I am mostly writing JESON text, I wanted the format to be as simple and visually appealing as possible.
The enhancements in JESON are summarized again as:
  1. keys in dictionaries do not need quotes if the word is all alphanumeric characters + '_'
  2. single quotes are interchangeable with double quotes
  3. the '=' character is interchangeable with the ':' character
  4. the ':' or '=' characters are optional
  5. Outer object is assumed to be a dictionary if '{' or '[' does not start the text
  6. "()" characters are interchangeable with "{}"
  7. commas separating array items and dictionary key/value pairs are optional
  8. comments via "//" and "/**/" are supported
For my JESON implementation, I modified Stig Brautaset's json-framework, version 2.2.1. I mostly changed the parsing routines. I also rearranged some of the files and renamed classes to avoid confusion. Kudos to Stig for his wonderful JSON work. The JESON parser code and an example application can be fetched from the Osmorphis group. Currently this is an iPhone XCode project, but the JESON parser code should also be usable on the Mac. However, since I don't develop in Objective-C on the Mac, I cannot vouch for that. The project creates a static library, one that is usable in iPhone applications.

Including the JESON library

To use the JESON library in your project, XCode seems to make the process a bit convoluted. Perhaps there are easier ways, but I follow the instructions given here at Coding Ventures. Be sure to change your "search for headers" setting to include ../jeson/JESON, which is where the JESON header files are located.

Accessing the JESON code

To access the JESON definitions in your code, you must import the header file: #import "JESON.h"

Parsing JESON

The primary use for JESON package is to parse it JESON text. JESON text might be in a file, inside your code, or come from the web. Where it comes from is of no concern to the parser. The JESON parser only parses strings, so wherever it comes from, you have to get it into an NSString object. There are a couple approaches you can take to parse JESON text. The first way is to directly call the JESON parser: JESON* parser = [JESON new];
id root = [parser parseString:myJESONText];
[parser release]; What is put into root depends on the JESON text. If the topmost container is a dictionary, then root will be an NSDictionary. If it is an array, then root will be an NSArray. As mentioned in part 1, JESON does not support JESON fragments. The topmost object will be either an array or a dictionary. If there was an error parsing the JESON text, then parserString: returns nil. In order to get the actual error, look at the error property of the parser: if(root == nil) {
NSLog("Error parsing JESON: %@", [parser.error localizedDescription]);
} The second way of parsing JESON is via a category extension made to NSString. If you have your JESON text in a NSString object, then simply call the parseAsJESON method to return the root object: NSString* myJESONText;
// ....
id root = [myJESONText parseAsJESON]; Writing JESON JSON can also be written given a dictionary or an array. Obviously, the objects inside these containers must be compatible with JSON/JESON. Currently, the JESON package does not create JESON syntax; it creates pure JSON. This is a low priority for me at the moment, since I don't have a need to reverse the parse operation and actually write JESON. This will be added later. In the meantime, the write code is essentially the same as what Stig has in his original json-framework package. NSMutableDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:...];
JESON* writer = [JESON new];
NSString* JESONText = [writer createFromObject:dict];
[writer release];

Some Examples

The following are some code snippets from the TableFormEditor package which is currently being enhanced to allow configuration via JESON/JSON. Since the TableFormEditor package will accept a dictionary of configuration information, you could also use a plist if you so desire, but I find JESON much more to my liking. As you can see below, it's not a bad format to enter this type of information. Here is an example of how to configure a particular TableFormEditor instance.

title = 'Person Record'
showLabels = true
allowDelete = true
labels { delete = "Delete Record", save = "Save", cancel = "Cancel" }
firstFocusRow = 1

fields [
# fields will be displayed in this order
{
  name = "Name"
  textfield {
     adjustsFontSizeToFitWidth = true
     minimumFontSize = 7.0
     autocorrectionType = 'No'
     autocapitalizationType = 'Words'
     text= ''
  }
}

{
 name = "Age"
 textfield {
   keyboardType = 'NumberPad'
   text = 23
 }
}

{
  name = "Homepage"
  textfield {
    // can also use the longer enum name
    keyboardType = 'UIKeyboardTypeURL'
    autocorrectionType = 'UITextAutocorrectionTypeNo'
    autocapitalizationType = 'UITextAutocapitalizationTypeNone'
    // some enums can use booleans
    clearButtonMode = true
    text = ''
  }
}

{
 name = "Password"
 textfield {
   secureTextEntry = true
   text = ''
 }
}
]

I will discuss the new TableFormEditor in another post; the example above just shows the type of input that is expected. The new initializers for the TableFormEditor class now take a template of type NSDictionary*. The template is the above data, parsed of course. The following code is what reads in the above text from a file and parses it into a NSDictionary root:
// read the JESON file in
NSDictionary* templ;
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"formTemplate" ofType:@"txt"];
if (filePath) {
NSString *myText = [NSString stringWithContentsOfFile:filePath];
templ = (NSDictionary*) [myText parseAsJESON];
}
This root is then passed to the TableFormEditor initializer. The initializer then initializes itself based on the key/values above. Before, you had to do this via properties in code. Now it can be done in a config file. Here is a snippet of code that looks at the first 5 settings:
// get values from template
if(templ) {
id obj;
if(obj = [templ objectForKey:@"title"]) {
   self.title = obj;
}
if(obj = [templ objectForKey:@"showLabels"]) {
   self.showLabels = [obj boolValue];
}
if(obj = [templ objectForKey:@"labels"]) {
   NSDictionary* l = obj;
   if(obj = [l objectForKey:@"save"]) {
       self.saveButtonLabel = obj;
   }
   if(obj = [l objectForKey:@"cancel"]) {
       self.cancelButtonLabel = obj;
   }
   if(obj = [l objectForKey:@"delete"]) {
       self.deleteButtonLabel = obj;
   }
}
if(obj = [templ objectForKey:@"allowDelete"]) {
   self.allowDelete = [obj boolValue];
}
if(obj = [templ objectForKey:@"firstFocusRow"]) {
   self.firstFocusRow = [obj intValue];
}
}
As you can see, there is still a fair bit of parsing to do, but this is only written once. The clients of the TableFormEditor just write config files in JESON (or a plist if that's their desire). In future articles I'll go into more detail of how to use the new TableFormEditor package, and I'll discuss scripting possibilities with JESON.

September 10, 2009

JESON: Enhancing JSON Syntax

JESON

When I work in Swing/Java, I don't write out all the code to build the components to construct the GUI. How tedious! Instead, I make use of a technology based on SwiXml to describe my GUI layouts via an external description file in XML.

Since working on the iPhone, I find myself doing similar tedious coding. Even with my own TableFormEditor, I am doing lots boring setup coding that can best be done in a string-based description. I like to call this technique "configuration-based coding". In short, this technique replaces code with a more terse description that achieves the same thing.

The benefits of using such a technique is that you can tweak your "configuration file" or "script file" without changing your code. This also implications with the iPhone's 3.0 support for downloading software updates inside your app. Apple doesn't prescribe what these downloads are, except that they aren't "code". So configuration files seem like a logical choice here.

So my desire was something like SwiXml to use on the iPhone. However, I don't want XML; it is a pig to parse and not fun at all to hand-edit. Certainly on the iPhone plists can achieve my requirements. Plists can be persisted to a file and read back in quite easily. Plists also support basic constructs like dictionaries, arrays, strings, etc. But I wanted something more friendly for hand editing. I don't like the clunky interface of the plist editor. So I started looking at JSON.

JSON is one of latest developments to gain a lot of hype. The data interchange format JSON (JavaScript Object Notation) started life during the AJAX craze. Many think JSON spells the end for XML. JSON can do many of the things that XML can, but in a simpler, cleaner way. I'm all for anything that would put XML to rest for good. XML is an abomination; the idea is great, the implementation is awful. There are even several decent Objective-C implementations for JSON reading and writing. I'm on the JSON bandwagon.

Almost.

As I worked with JSON a little bit, I started to realize that JSON is only marginally better than XML from a syntactical standpoint. I understand JSON is a subset of Javascript expression syntax, and thus its specification is limited to the confines of what Javascript can handle. But this argument is becoming more and more moot given the dangers of actually evaling JSON. People are saying you should never, ever do this. (Check out this blog article.) I don't use Javascript and probably never will. So why should I suffer through its syntax?

To address the bad taste JSON leaves in my mouth, I have come up with a set of enhancements to the JSON syntax. I call this "JESON" (I stuck the "E" where I did because "JES" happens to be my initials). JESON can read and write original JSON just fine, but it also supports the syntax enhancements described below. The implementation I have modified is Stig Brautaset's wonderful json-framework package available at http://code.google.com/p/json-framework/. This package has a simple enough parser to allow these changes to be made quite easily.

So, what's my beef with JSON syntax? There are several minor annoyances, but annoyances nonetheless. JSON incurs plenty of useless noise which I would prefer not to see or type. Let me demonstrate with an example of JSON syntax.

This example was swiped from the JSON website example page:

{
  "menu": {
     "id": "file",
     "value": "File",
     "popup": {
         "menuitem": [
            {"value": "New", "onclick": "CreateNewDoc()"},
            {"value": "Open", "onclick": "OpenDoc()"},
            {"value": "Close", "onclick": "CloseDoc()"}
         ]
     }
  }
}

JSON syntax violates several of my syntax rules I apply to good languages. The first violation is this syntax rule: "Don't require syntactical elements that serve no purpose".

I am a minimalist when it comes to syntax. Less is better. You have to admit when looking at the above example, JSON has lots of punctuation. But is it all necessary?

According to the spec, a dictionary key must always be a quoted string. Why? Unless the key can be anything but a string, what is the point of the quotes? For most needs, the key is always an identifier, an alphanumeric word. Requiring the quotes here serves no purpose. And the busy little tick marks make it hard to quickly discern between the keys and values.

To fix this, JESON makes the quotes on the keys optional:

{
  menu: {
     id: "file",
     value: "File",
     popup: {
         menuitem: [
            {value: "New", onclick: "CreateNewDoc()"},
            {value: "Open", onclick: "OpenDoc()"},
            {value: "Close", onclick: "CloseDoc()"}
         ]
     }
  }
}

To me, this one little change makes a big difference. I find this cleaner and easier to read. If your key happens to have spaces or weird characters in it, then you will have to keep the quotes there.

Here is another one of my rules of a good language: "Minimize shifted characters as much as possible".

I type a lot. A LOT. By the end of the day, my wrists and fingers are pretty stressed. Thus this rule is designed to minimize moving the fingers over to that shift key. Typing CamelCase code all day long can really kill me. So in the context of JSON, I have two problems: the colons and the double quotes.

Using a colon for assignment is certainly non-intuitive. The predominant operator for assignment in most modern languages is the equal sign. The '=' character has more "width", and therefore it is easier to see than the tiny colon. And best of all, the '=' requires no shift to type.

{
  menu= {
     id= "file",
     value= "File",
     popup= {
         menuitem= [
            {value= "New", onclick= "CreateNewDoc()"},
            {value= "Open", onclick= "OpenDoc()"},
            {value= "Close", onclick= "CloseDoc()"}
         ]
     }
  }
}

Now let's look at the quotes. Since JSON has no distinction between characters and strings, we can optionally support single quotes. Some may like the bolder style of double quotes, and even I prefer them sometimes when I want them to stand out more, but there is no reason not to support single quotes. And single quotes require no shift.

{
  menu= {
     id= 'file',
     value= 'File',
     popup= {
         menuitem= [
            {value= 'New', onclick= "CreateNewDoc()"},
            {value= 'Open', onclick= "OpenDoc()"},
            {value= 'Close', onclick= "CloseDoc()"}
         ]
     }
  }
}
I left some double quotes in the example to show they can be mixed. You can't mix them on the same string, though.

Hey, now it's looking better. But I'm looking at rule 1 again (no useless characters) and I see 2 more useless characters. The = character, which I so triumphantly argued for, now looks superfluous. But you might like them, you might not. I prefer to not use them for assigning a dictionary or array, but to use them for simple key/value pairs inside a dictionary.

{
  menu {
     id='file',
     value='File',
     popup {
         menuitem [
            {value='New', onclick="CreateNewDoc()"},
            {value='Open', onclick="OpenDoc()"},
            {value='Close', onclick="CloseDoc()"}
         ]
     }
  }
}


The other useless characters are the commas. They add no value to the parser, so they are strictly visual. Thus, JESON makes them optional. To me, they help separate key/value pairs when they are all in the same line, but commas are worthless when elements are separated across lines. My preference is to remove the commas between those elements one their own line, but use commas between elements that are in the same line:


{
  menu {
     id='file'
     value='File'
     popup {
         menuitem[
            {value='New', onclick="CreateNewDoc()"}
            {value='Open', onclick="OpenDoc()"}
            {value='Close', onclick="CloseDoc()"}
         ]
     }
  }
}

One change I made to Stig's JSON implementation I modified was to remove support for "fragments", which are not strict JSON anyway, and comments in the code alluded that it was a deprecated feature. With fragments removed, JESON must begin with either a dictionary or an array, nothing else. The majority of the JSON/JESON text I use has a dictionary as the outer object. I wanted that to be the default so I didn't need the outer {} characters. I enhanced JSON to assume the object is a dictionary if '{' or '[' were not the first non-whitespace characters. Thus, the following is exactly the same as the above, only a little cleaner:

menu {
    id='file'
    value='File'
    popup {
        menuitem[
           {value='New', onclick="CreateNewDoc()"}
           {value='Open', onclick="OpenDoc()"}
           {value='Close', onclick="CloseDoc()"}
        ]
    }
}

Man, that is looking sweet. It is a far cry better than the noisy original, which I'll put up again just so you can compare:
{
  "menu": {
     "id": "file",
     "value": "File",
     "popup": {
         "menuitem": [
            {"value": "New", "onclick": "CreateNewDoc()"},
            {"value": "Open", "onclick": "OpenDoc()"},
            {"value": "Close", "onclick": "CloseDoc()"}
         ]
     }
  }
}
One other enhancement in JESON is to make () synonymous with {}.

menu(
  id='file'
  value='File'
  popup(
      menuitem[
         {value='New', onclick="CreateNewDoc()"}
         {value='Open', onclick="OpenDoc()"}
         {value='Close', onclick="CloseDoc()"}
      ]
  )
)

Now some of those dictionaries look like function calls. Why would I want this? I have a vision of a lightweight scripting language based on the JESON syntax. Consider the following:

tableViewController {
   if [x == true] then {
       type='grouped'
       doSomething(var='value')
   }
   else {
       type = 'ungrouped'
       doSomethingElse(var1='value1', var2='value2')
   }
}

Kinda sorta looks like code, doesn't it? But it is actually valid JESON. The original JSON would look like this:

{
"tableViewController" : {
    "if" : ["x" == true], "then" : { "type" : "grouped", "doSomething" : { "var":"value"} },
    "else" : { "type" : "grouped", "doSomethingElse" : { "var1":"value1", "var2":"value2"} }
}
}

The usefulness of this may seem dubious, but I will discuss this in part 3.

One other thing that JSON doesn't support is comments. For any hand-edited configuration language, comments are mandatory, so JESON adds support for the basic // and /**/ formats:
// this is a menu
menu(
    id='file'
    value='File'
    popup(
        menuitem[
           // removed this one for now
           /*{value='New', onclick="CreateNewDoc()"}*/
           {value='Open', onclick="OpenDoc()"}
           {value='Close', onclick="CloseDoc()"}
        ]
    )
)

So that's it for JESON. Not much, really, but to me it makes it much easier to write and read. Here is a summary of all the enhancements JESON makes to the JSON syntax:

  1. keys in dictionaries do not need quotes if the word is all alphanumeric characters + '_'
  2. single quotes are interchangeable with double quotes
  3. the '=' character is interchangeable with the ':' character
  4. the ':' or '=' characters are optional
  5. Outer object is assumed to be a dictionary if '{' or '[' does not start the text
  6. "()" characters are interchangeable with "{}"
  7. commas separating array items and dictionary key/value pairs are optional
  8. comments via "//" and "/**/" are supported

In part 2 of this series, I'll discuss where to get the JESON parser and how to use it.







August 3, 2009

Assigning Delegates

Kind reader Demitri Muna pointed out a flaw in my TableFormEditor package. I stumbled into a trap I fear many newbie Objective-C programmers also fall into: that of retaining delegates. It is a two-line change, but I feel this issue is important enough to write about it.

The basic problem is a retain cycle which results in a memory leak. This has been fairly well documented in this thread, but I will go into more detail here in the context of the TableFormEditor.

In this context, there are 2 actors involved:

  1. the client object
  2. the TableFormEditor object

When the client object creates a TableFormEditor instance, it needs to pass a delegate to handle the various callbacks. Typically, but not required, the delegate is the client object (i.e. self).

The TableFormEditor has this declaration in its .h file:

@property (nonatomic,retain) id <TableFormEditorDelegate> delegate; 


So what this means is that the client has a retain on the TableFormEditor (because it created it via [alloc]), and the TableFormEditor instance has a retain on the client (via the "retain" keyword in the @property declaration).

This is the dreaded A -> B and B -> A scenario described in the Stack Overflow thread mentioned above. When you are in this situation, A and B will never go away because B has a retain on A that will not release until B goes away. But B won't go away until A goes away. Result: memory leak!

However, all is not lost if you followed the pattern I have in the TableFormEditor example. In the example, I do not keep the TableFormEditor object around. As soon as I push it on the Navigation Controller's stack, I release it:

   
// stick the editor onto the navigator's stack 
[self.navigationController pushViewController:form animated:YES];      

// release the form since the navigator retained it 
[form release]; 


But, if you retain the pointer to the TableFormEditor, like keeping it in an instance variable, then you will likely end up with a memory leak.

Thus I have released version 1.6 of the TableFormEditor class to make this change:

@property (nonatomic,assign) id <TableFormEditorDelegate> delegate; 


This simply assigns the pointer without bumping up the retain count. This breaks the cycle and the potential for memory leaks.

For more information on retain cycles and how to prevent them, I urge you to check out this blog article at Cocoa With Love.





July 6, 2009

Changing the Accessory View

In my application, I want to replace the button in the accessory view area of a table cell with my own button. I want it to look like this:
Clicking on the cell should produce the callback tableView:(UITableView *) aTableView didSelectRowAtIndexPath:(NSIndexPath *) indexPath. However, when the pencil icon is hit, I want it to do a different callback. I didn't want to make a custom table cell class, and from reading the documentation, it appeared relatively straight forward to use the existing table cell class. All I had to do was set the cell property accessoryView to something else. Here is what the SDK documentation says:
@property(nonatomic, retain) UIView *accessoryView Discussion If the value of this property is not nil, the UITableViewCell class uses the given view for the accessory view and ignores the value of the accessoryType property. The provided accessory view can be a framework-provided control or label or a custom view. The accessory view appears in the the right side of the cell. If the cell is enabled (through the UIView property userInteractionEnabled) , the accessory view tracks touches and, if tapped, sends the accessory action message set through the accessoryAction property.
Ok, sounds simple enough, so I went ahead and coded up what I thought was a trivial solution. I picked a UIImageView to put into the accessoryView. I was careful about setting the userInteractionEnabled flag and everything. Here is the snippet of code I came up with (which belongs in the cellForRowAtIndexPath method, in the case we have to create a new UITableCell object):
// stick the pencil icon on the accessory view
UIImageView* pencil = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon-pencil.gif"]];
pencil.userInteractionEnabled = YES;
pencil.frame = CGRectMake(0, 0, 15, 15);
cell.accessoryView = pencil;
cell.accessoryAction = @selector(didTapEditButton:); 
Well, this didn't work. All taps on the image produced the didSelectRowAtIndexPath callback. I re-read the documentation on accessoryView. That last sentence mentions the accessoryAction property, so I thought I should take a peek at that:
@property(nonatomic) SEL accessoryAction Discussion If you specify a selector for the accessory action, a message is sent only if the accessory view is a detail disclosure button—that is, the cell's accessoryType property is assigned a value ofUITableViewCellAccessoryDetailDisclosureButton. If the value of this property is NULL, no action message is sent. The accessory view is a UITableViewCell-defined control, framework control, or custom control on the right side of the cell. It is often used to display a new view related to the selected cell. If the accessory view inherits from UIControl, you may set a target and action through the addTarget:action:forControlEvents: method. See accessoryView for more information.
Hmmm. That very first sentence says I can't do this with a custom view. But the next paragraph states I can just use the addTarget:action:forControlEvents: method. (Then it makes a circular reference back to accessoryView for more info, which doesn't offer more info.) But a UIImageView is not derived from UIControl, so that is not available. The solution to this mess is to use a UIButton instead of a UIImageView. UIButtons are UIControls, so the final code looks like this:
// stick the pencil icon on the accessory view
UIButton* pencil = [UIButton buttonWithType:UIButtonTypeCustom];
[pencil setImage:[UIImage imageNamed:@"icon-pencil.gif"] forState:UIControlStateNormal];
pencil.frame = CGRectMake(0, 0, 15, 15);
pencil.userInteractionEnabled = YES;
[pencil addTarget:self action:@selector(didTapEditButton:) forControlEvents:UIControlEventTouchDown];
cell.accessoryView = pencil; 
This time it works. I get the desired callback when the pencil icon is touched. The summary is: use a UIControl based widget in the accessoryView, and ignore the accessoryAction property.

June 9, 2009

Java on the iPhone?

Is it possible? Can you run Java on the iPhone? Well, no, at least not at this time. Perhaps never, due to the rules Apple have in place disallowing interpreted languages from operating on the iPhone. This is a real shame because quite frankly, Objective-C is not an easy language to work with. And since it is the only language we have to work on for the iPhone, our hands are extremely tied. (One could argue that Objective-C++ allows C++, but in my opinion, this is a much uglier situation than just coding in Objective-C.) I am a former Java coder. Java may not be the most enabling language (think Python or Groovy), but the grammar is clean and simple and arguments about Java being too verbose are lost when comparing it to Objective-C. I like the power of the Cocoa-Touch run-time environment. However, the vehicle to get to that power (Objective-C) is a nightmare. Objective-C is clunky, verbose, inconsistent, and archaic. It is loosely based on SmallTalk, a relatively unused language in the industry. There's a reason for that. To me, doing anything in Objective-C is painful. Take the mundane task of creating a dictionary and adding a key/value pair to it. In Objective-C, it would look something like this:
NSMutableDictionary* dict;
dict = [[NSMutableDictionary alloc] initWithCapacity:3];
[dict addObject:@"Some data" forKey:@"key"];
I have many issues with this code:
  1. Why does Objective-C insist of dealing with pointers? Since you can't instantiate an object on the stack like you can in C++, having to specify the "*" character is superfluous. The fact that these are pointers should be hidden, as they are in Java. In the rare cases you need to actually refer to the class name and not the pointer, use some other syntax.
  2. The [object method] call syntax is really whacked. My opinion is that this is not an intuitive syntax, nor is it easy to read or write. It is nearly impossible to visually parse, especially with nested calls.
  3. Semicolons? Come on. There is no reason why a language parser cannot figure out the end of a statement. These are artifacts from the days of Pascal and C when they didn't know better. Tcl, Groovy, Python, Ruby, JavaScript, et al prove that semicolons are extraneous syntax fluff. It's a shame that most programmers accept them as the de facto for languages, when in fact they indicate a poorly designed grammar.
  4. Look how verbose and awkward it is to add a single element to the dictionary. I get carpal tunnel syndrome just reading Objective-C code. Objective-C forces you to use positional arguments and named arguments at the same time. If it wasn't for Xcode helping to write Objective-C, it would be a horrid language to type.
  5. I miss the commas between arguments. These are not needless syntactical fluff, as the "*" and ";" characters are. Commas help visually separate arguments. Without them, the args all blend together and make it hard to read.
  6. What's with the @ characters in front of strings? I understand they are trying to differentiate between C-style string constants and NSString constants, but why give the simpler syntax to C? I have never used a C-style string in an Objective-C program. I would have made "string" automatically be an NSString constant, and if you want a dinosaur C-style string, then use @"string".
Okay, that's six major complaints in just 3 lines of code. This doesn't even go into my other major beefs, such as separate files for class definitions and declarations, the @property/@synthesize malarkey, the use of "@end" as a block terminator, etc. Java can do the same task a little better and with a much cleaner syntax:
HashMap dict;
dict = new HashMap(3);
dict.put("key", "Some data");
It still has those dumb semicolons, but this is still a major improvement. I know all this bitching and moaning doesn't accomplish much. Objective-C is the tool we have to work with on iPhone development. There is nothing you can do about it. Adapt and move on. And adapt I did. I tolerated Objective-C's quirks for months. But I always thought about how much easier and productive it would all be in another language. I couldn't let it go. Then I came up with an idea: What if I just used the syntax of Java, and not the Java run-time environment? What if I wrote a translator, one that translated Java code into Objective-C? How hard would it be? I think this is quite possible, as long as you lay down a few ground rules. I have accumulated a fair number of these ground rules and revelations from tinkering with prototypes. The above Objective-C code could look like this in Java syntax:
NSMutableDictionary dict;
dict = NSMutableDictionary.alloc().initWithCapacity(3);
dict.addObject("Some data", forKey="key");
Notice a few things different? But some things are the same. The most important aspect of this is how we pass parameters. The first parameter is passed like normal, but all subsequent parameters are passed as if they are keyword parameters (ala Python). Although this is parseable Java syntax, it wouldn't compile. But it can be translated to Objective-C very easily. The whole idea is boiled down to this: In Xcode, write your iPhone software using Java syntax. Calls to the Objective-C runtime and Cocoa Touch are pretty much the same. There are no separate .h and .m files, just .java files. Then run the Java code through a translator that generates the Objective-C .h and .m files, which then get compiled. Xcode provides the ability to run preprocess steps in a build operation. So you could set up your builds to translate your Java source to Objective-C, then the normal build process would take it from there. Another benefit is that Xcode will think you're typing in Java code (because you are, sort of), so you will get all the nice keyword highlighting and other editor shortcuts. This idea is not limited to Java. Although Python does not have static typing, the ShedSkin project proves that you can translate Python to C++, so it is likely possible to also translate Python to Objective C. But this situation is not perfect. For starters, any compile errors in the Objective-C source will have to be corrected in the original Java source. Unless you want to abandon your original source, you should never edit the generated Objective-C source code. Runtime debugging will have to be in Objective-C. For some, these problems may be enough to warrant this as an exercise in futility. I will reserve judgment until trying it in production software rather than just in tinkering. This introduction is just to whet your appetite of the possibilities. This project I call "Typhoon". Typhoon will comprise the set of language translators and any additional run-time support necessary. In future articles, I will describe some of the ideas of Typhoon. I invite readers to leave comments on what you think about this idea. Is it worth pursuing? Or is it an idiotic waste of time? Please let me know.

June 4, 2009

Multiple Parameters to Threads

This hint is fairly trivial, but I was surprised I could not find any information on this little "problem". I wanted to pass more than one parameter to a thread entry method. The standard NSThread class only supports 0 or 1 parameter to be passed, as can be seen in this initializer:

- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument

Another way of starting a thread is with the method:

+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument

But as you can see, this has the same limitation. The object parameter can be nil or some other parameter, but at most 1 parameter can be passed. Even the more modern NSOperation class has this same limitation and its remedy is pretty much the same as described here. There are two ways I see to overcome this limitation. One is more complicated than the other, but I will present both.  

Subclassing NSThread

The more complicated way is to subclass the NSThread class and override the main method to be your thread entry point. Since you create your own class, your initializer can accept any number of parameters, which you assign to instance variables. Then the main method can easily access this data:


@interface MyThread : NSThread
{
  NSString* data1;
  NSInteger data2;
}

- (id) initWithData1:(NSString*) data1 andData2:(NSInteger) data2;
- (void) main;

@end

@implementation MyThread

- (id) initWithData1:(NSString*) data1 andData2:(NSInteger) data2
{
  if((self = [super init])) {
    // save off our parameters
    self.data1 = data1;
    [self.data1 retain];

    self.data2 = data2;
  }

  return self;
}

- (void) main
{
  // no need to call [super main], as per the Apple reference docs
  // do whatever your thread needs to do
}

- (void) dealloc
{
  [data1 release];
}

@end


In order to kick off this thread, you do something like this:


// initialize it, passing all your parameters
MyThread* thread = [[MyThread alloc] initWithData1:@"hello there" andData2:23];

// now start it
[thread start];

// done with it
[thread release];


As you can see, this can be a bit involved, forcing you to create a new class, but it gets the job done.  

Stuffing Parameters

The other way is simpler, but at the same time a little clunkier. This way uses the simple initializer or the detach method as mentioned above. The way to get multiple parameters passed is to cheat: we pass a single container that holds all our parameters. Since this parameter is defined as id, it can be anything (as long as it is an object and not a primitive type). The perfect container is an NSArray. However, this is where things get a little clunky. First you have to create the array and populate it with your data. Worse is the fact that you can only put class objects into the array; scalars like integers will have to be converted to an object before adding.


// fire up a thread
[NSThread detachNewThreadSelector:@selector(myMain:)
                      toTarget:self
                    withObject:[NSArray arrayWithObjects:@"hello there",
                                        [NSNumber numberWithInt:23], nil]];


And then your thread entry method must pull the parameters back out of the array:


- (void) myMain:(NSArray*) parameters
{
 NSString* data1 = [parameters objectAtIndex:0];
 NSInteger data2 = [(NSNumber*) [parameters objectAtIndex:1] intValue];

 // the rest ...
}


Neither of these two solutions are perfect. The best solution, of course, is to write your thread code such that it doesn't need more than one parameter, but sometimes this is unavoidable. If any readers out there have any other ideas to solve this, I would love to hear them!

May 29, 2009

Trapping the UINavigationBar Back Button (part 3)

I have covered the topic of trapping the back button in order to do something. These previous forays are part 1 and part 2. I had implemented my solution from part 2, and it is working well. However, I am always on the look out for a better, cleaner solution. Just recently, an anonymous commenter pointed out something I had not noticed before: the UINavigationBarDelegate prototype has a method called navigationBar:shouldPopItem: It is called just before the item is popped. If it returns NO, then the pop won't actually happen. But this can be the perfect way to insert some logic before the pop happens (and return YES at the end). Here is how you would implement your back-button press event logic:
- (BOOL)
navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
{
   //insert your back button handling logic here

   // let the pop happen
   return YES;
}  
This is so much cleaner than my previous solution. I love it! Thanks to whomever pointed out the obvious.

May 20, 2009

A Background Task Class

I am working on an app that makes XML calls to a web service. At first, I made the calls within the main thread and waited for the results to come back. Not surprising, when these calls took longer than usual, the user interface suffered. Basically, the UI locks up while waiting for a response from the web service. This is because the main thread is busy and cannot service UI-related events, such as touch events. What I had to do was make the web service calls in a separate thread so that the main thread can continue to service the UI. I coded up a few uses and I quickly discovered that my app wanted two different behaviors while making web service calls in the background. These behaviors are:
  1. The background task should operate transparently. It would only alert the user if the operation timed out,
  2. The user had to wait for the operation to complete, but user is given the option to cancel the background operation.
I decided to create a utility class to encapsulate these behaviors and make it all a little easier. Thus I created the BackgroundTask class, which I present here. What does it do? The BackgroundTask class is like a NSThread class; it allows you to spin off code in a separate thread. But this class is more powerful because it supports the two behaviors described above.

The Behaviors

First, let's discuss the desired behaviors in a little more detail. Behavior #1 listed above is for tasks that are low priority and don't require the user to wait for it to complete. The task is kicked off in the background, and the main thread retains control for the user to do whatever they need. They don't even know there is something going on in the background (except for the spinning network access icon in the status bar). The only feedback the user may get is if the operation timed out, meaning it failed. Each task created is given a timeout value. If the operation is not complete by this timeout period, then an alert message pops up that displays something like this:
The alert message displayed below "Operation failed" is also configurable when you create the task object. Behavior #2 is more of a blocking operation, but with the option to cancel it if the user feels it is taking too long. This is useful for higher-priority tasks that require the user to wait until it is complete. For example, if the user hit a refresh button to update the items displayed in a table, it kind of makes sense for the refresh to complete before continuing. When running a task like this, it displays a modal dialog like this:
I added a little optimization to this behavior as well. This dialog won't pop up for X number of seconds, where X is configurable. This is to avoid those situations where the background task completes almost immediately. When this happens, it was silly for the alert to pop up then disappear so fast that the user couldn't even read what it said. So the alert will only come up if the task takes longer than X seconds.

Instantiating

Since the BackgroundTask class supports two different behaviors, it also supports two different initializers. This first one initializes the object for behavior #1, where the task runs the background without any user interaction:
BackgroundTask* task = [[BackgroundTask alloc] initWithTarget:self
   selector:@selector(executeEmailPage:)
   argument:myparent.page
   timeout:40.0
   alertMsg:@"Attempt to email page timed out"]; 
The target/selector arguments specify the method to run in the new thread. The argument is optional data you can pass to the above method. Timeout specifies how long to give that thread before putting up an alert. And the final argument is the alert message to put up when the operation times out. This next initializer is for behavior #2, where the user can cancel the operation:
BackgroundTask* task = [[BackgroundTask alloc]
   initWithTarget:self
   selector:@selector(backgroundRefresh)
   argument:nil
   waitBeforeAlert:0.5
   title:@"Refreshing data"
   msg:@"Standby while refreshing pages"]; 

The target, selector, and argument parameters are the same as the first initializer. The waitBeforeAlert parameter specifies how long to give the operation to complete before putting up the modal box. The title and msg parameters allow you to configure the text displayed in the modal dialog.

Usage

To use the BackgroundTask object after you create it is very simple:
// start the background thread
[task start];

// release it since we don't need it anymore
[task release]; 

Getting The Code

The code for the BackgroundTask class is available on the Osmorphis google group. You can download the .zip archive here. Hopefully its usage is clear enough that you can easily stick the code in your own project and begin using it right away.