December 7, 2010

Welcome Back

Welcome back to me, after a long 10 month silence. I have been extremely busy with our iPhone app, getting a new job, moving, buying a house, settling in, etc.

The current excitement is completing our long overdue iPhone app. After nearly 2 years in the making, it was finally accepted into the Apple Store. Check it out, if you’re a Colorado traveler:


I’ve learned a lot these past 10 months, and hopefully I can share some of that knowledge here on the blog. So until next time!

February 21, 2010

Static Libraries in iPhone Projects (Part 3)

This is an addendum to my earlier 2-part article on how to create and share static libraries for iPhone projects. Part 1 discusses how to setup Xcode to create a static library target. Part 2 discusses how to share a reference to that library from within another project.

This addendum to address a missing step from part 1. According to Apple documentation, static libraries do not need to be code signed. This is only important if you are an "official" Apple iPhone developer ($99/year).

To remove code signing, select the library target under Groups & Files > Targets. Double click the target to bring up the info dialog window. Select the Build pane.

Scroll down to the Code Signing group. It should look something like this:

See the highlighted line and how it says "iPhone Developer"? Click on that value and you will get a little menu. Select "Don't Code Sign".

That's it!

February 8, 2010

Static Libraries in iPhone Projects (Part 2)

This is the second part of a two-part article on how to create and use static library projects in your iPhone apps. In Part 1, I discussed how to create a static library project, as well as including a test application.

In this part, I will describe how to include this static library project into other projects. The steps outlined here offer several advantages. One is the ability to load the static library project simply by double-clicking on the project reference in your other project. This brings up a new Xcode window for the library project, where you can browse the code and even make changes. If you do make changes in the static library code, not to worry because when you build your application, it will also build your static library project.

In order for this convenience to work, though, you must follow these steps closely. Xcode is powerful, but it is also non-intuitive and finicky in some areas.

In this part, I will continue my example of using my BackgroundTask static library I put together in the first part. This static library is available with its project and source code at the Osmorphis group. I will be "importing" this library in another project I am working on that needs the BackgroundTask functionality.

So let's begin!

Bringing over the static library project


Bring up your client project, the project that wants to use the static library, in Xcode. To bring over the library project, all you need to do is drag the project over. You can do this one of two ways:

You can drag the whatever.xcodeproj file (it is really a directory) from the Finder. This is the file to drag over:



The other option is to drag the project from one Xcode window. This is the root element of the Groups & Files tree:


Where you drag this is the Xcode project of the application that wants to use the library. You can drag and drop anywhere in the Groups & Files tree. When you drop, a dialog sheet comes down asking for the details of what you want to do:


Be sure you do not select "Copy items..." and the reference type is selected as "Relative to Project".

What you'll see after this is a new item in your Groups & Files tree with the same blue "A" icon for Xcode projects. Here is an example of my application that has several static libraries referenced:


If you have many of these, you could group them in a folder called "libs" or something like that.

Specify the Product


Now you have to tell Xcode what products from this external project you are interested in. Select the library project you just dropped in. If you don't see the "Detail", "Project Find", ... tabs, then you may have your editor window taking up the entire content pane, so drag down the split pane to show:


As shown above, you want to select the library product, but not the test app.

Locate Header Files


You need to tell your application where to find the header files of the referenced library. It would be nice if the reference would be sufficient, but it is not, so you have to muck with compile flags.

Double-click on the project of your target application. Important: don't click on the root element of the Groups & Files tree. This is not what you want. You want to click on the application in the Targets element of the tree. If you edit the wrong one, you'll be banging your head on the wall for hours with missing header file problems (like I did).

Go to the "Build" Tab.

Make sure you are editing for all configurations, since the location of the header files won't change, if you use the instructions below.

We need to edit the "User Header Search Paths" property, so go ahead and start typing this in the search box (or you can hunt for it manually). Double click on the value field. This should bring up a dialog that may contain other entries.

Add a new entry for your static library. The public header files are stored in a long-winded location, and it depends on whether you're building a Debug or Release build, and if you're building for the simulator or an actual iPhone device. These specifics are encoded in some variables. So copy and paste the following for your new user header search path:

${PROJECT_DIR}/../staticlib_project/build/${BUILD_STYLE}-${PLATFORM_NAME}/usr/local/include

Replace the "staticlib_project" part with the directory of the static library you are trying to set up. This assumes that your static library project is in a peer directory.

I have several static libraries referenced in my application, so my user header search paths property looks like this:


The ${BUILD_STYLE} and ${PLATFORM_NAME} variables will be replaced automatically to match your current build. This is how we can use the same settings for all builds.

Setting Linker Flags


While we're in the build properties, we need to add an option to the linker flags: -ObjC. This tells the linker to load all classes and categories from static libraries. If you don't do this, then you may get linker errors.

Clear out the "user header search" in the search box and type "other linker flags". Add -ObjC to this:


Set the Dependency


Now we would like to set a dependency on the library so that it will get compiled when you compile your application. Double-click on the application under Targets, and go to the "General" tab.

Click on the + button for the Direct Dependencies. Select your new library.

You also may have to add the library to the Linked Libraries panel, also found on the "General" tab. Hit the + and select the library. I have seen times where the library is not available to choose. In these cases, drag the .a file from the project down to the "Link Binary With Libraries" section of the target.

Good to Go


At this point, your static library should be properly referenced. The nice thing about this setup is that your library is built whenever something is changed; no need to switch over to that project to build it separately. But, if you need to look at the source code, simply double-click on the project from your tree and the other project is opened up in a new window.

It is also to step into the source files of your referenced libraries in the debugger.

So stop dropping copies of reusable code into your projects. Build a library and reference them!

February 1, 2010

Static Libraries in iPhone Projects (Part 1)

One of the conclusions I have come to in my year of iPhone programming is this: in order to be successful in the iPhone market, a lone developer has to take advantage of code reuse as much as possible. We part-timer coders don't have time to reinvent the wheel for every project.

This is why Osmorphis has released a few libraries (frameworks) of reusable, general-use functionality. Things like the BackgroundTask class, the JESON package, plus a few others I have not released to the public (I gotta protect some of my "secret" weapons ;-) are all designed to be dropped into a project and used.

At first, this dropping of code, literally copying the code, worked fine. But I knew this was not a maintainable way to manage code, especially when the number of projects using these packages increased.

I finally bit the bullet and figured out how to maintain these packages in separate projects, build a static library, and reference them from other projects. This allows me to maintain the source code in one project. The product (the library) is referenced from other projects instead of the source code being copied in. This prevents several versions of the same code scattered throughout your projects.

(Note that these must be used as static libraries for iPhone development; Apple does not allow custom "frameworks" of shared libraries.)

In this two-part article, I will share how I do it. I feel this is a fairly cumbersome task, and I am constantly in awe with how both powerful and clunky Xcode is. There may be easier/better ways to do this. If you know how, please comment. I would love to simplify my process.

If you want to get to the summary of steps, jump to the bottom.

Part 1. Creating a Static Library Project


This first part discusses how to create a static library project. I will run through the steps of converting my BackgroundTask project to a proper static library. This project will contain the library itself plus a small test app.

In the part 2, I discuss how to reference this library project from another project in order to use it.

Create a New Project


From the menu in Xcode, select File > New Project...

Up comes a dialog that looks something like this:

You want to select iPhone OS/Application, and then select "Window-based Application". Hit the "Choose..." button, then name and locate your project where ever you see fit.

For my example, I created a new directory called backgroundtask and named the project the same, backgroundtask.

Your fresh project will look something like this:

Adding the Library Target

The project we've created so far is for a window-based application, so it is not set up for creating a library. But that's ok; we can use the application as our test app. I'll get to this later. For now, we need to create a new target for our static library.

Right click on the "Targets" element in the Groups & Files tree, and select Add > New Target...


Another dialog will come that looks something like this (your icon for static library may look like a red bullseye):

You want to select iPhone OS/Cocoa Touch, then select the "Static Library" target. Hit "next".

Enter the name of your library target. You probably want to use the "lib" prefix. For my example, I entered libbackgroundtask.

After you enter the name, you will be presented with a dialog of properties for this project:

Cleaning up the product name


Xcode will actually call your product "lib" + whatever you entered as the name. Which means my product name will be "liblibbackgroundtask". You can see this in the red entries under Products in the image below. I like the "lib" prefix as part of my target, but I want to clean up the product name to remove the extra "lib".

To do that, we need to make some changes on the properties dialog. If you already closed this, you can always bring it back up by selecting in the Groups & Files tree Targets > libwhatever > Get Info.


This will bring up the properties dialog again. Select the "Build" tab. The property we need to change is the Product Name property. You can find it by typing in the search box. All you need to type is "product n" before it shows up. This is what you'll see:


For libraries, Xcode prefixes the "lib" for you, so all we have to do is remove the "lib" already there. For me, I will change the Product Name to just "backgroundtask".

(Now, you might ask: Why didn't you name the target that in the first place? Because there was already a target with that name.)

Adding Code to the Library


Now we need to add some code to the library. In my case, and may be for most people, I already have the code. I have it sitting in another application. So I open a Finder window, locate the .h and .m files, and drag them to the Classes folder of the Groups & Files tree.

This will bring up a dialog asking you for more details what to do with these files:


Be sure to select "Copy items into..." because you want this project to "own" the sources to this code from now on. Other projects will merely reference this in the future. Select the libwhatever target to receive these files. The test app will actually link against the library rather than include the sources directly; this will test that we have the library built properly and can be linked.

Making things public


Now we should configure which header files are public. These files are distributed with your library. Private header files are not. So select "Targets/libwhatever" from the Groups & Files tree.

This brings up a window with the files you added to this target. Go to the "detail" tab if it's not already selected. Locate those header files you want to make private and change the role from "project" (the default?) to "public".


Setting Dependencies


Before we can try building this, we need to configure the test app to use the library. Select the application target under "Targets" in the Groups & Files tree. Right click on the target and select Get Info. Go to the General tab.

Here we need to add our library as both a dependency and a linked library. The first one makes sure the library is built when we build our application. The second one links in the library.

Click the little + button underneath each section and add the static library.




Compiling


Now we can try compiling our project. This should build both the test app and the library. Of course, we haven't done anything with our test app yet, so when you run it, all it does is display a white window.

To really test your library, you should add some code to the test app that uses/tests the library. I will leave this as an exercise for the reader.

What's Next?


At this point, you have a static library project ready to be used in other projects. In part 2 of this article, I will describe the steps to do this. As expected, it's not trivial.


Summary of Steps

I never remember how to do all the above. The following checklist is a quick list of steps to take to create a static library project. I use this myself to jog my memory what steps need to be done:

  1. File > New Project..., iPhone OS, Window-based Application
    1. enter name of project
  2. Targets > Add New Target..., iPhone OS, Cocoa Touch, Static Library
    1. enter name of library, with "lib" prefix
  3. Build tab, search for "product name"
    1. remove extra "lib" prefix from name
  4. Copy code files to project
    1. select "Copy items into..."
    2. select library as target
    3. deselect app as target
  5. Targets > lib..., "Detail" tab
    1. change role of public header files to "public"
  6. Targets > app, Get Info, "General" tab
    1. add library to dependencies and linked libraries
  7. Build and test

Acknowledgments


I used the following web sites to learn how to do this:

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.