Tuesday, December 6, 2011

Objective-C Tuesdays: more NSArray sorting

Welcome to another Objective-C Tuesdays. Last week, we looked at sorting C arrays and NSArrays. Today, we will continue looking at sorting NSArrays using NSSortDescriptors.

As we saw last week, the sorting methods of NSArray require you to specify a comparator in one form or another. When sorting an NSArray of simple objects like NSStrings or NSDates, the comparators are usually pretty simple to write and common objects often have useful comparator methods like -caseInsensitiveCompare: and -localizedCompare:.

When sorting NSArrays of more complex objects, writing comparators is often more tedious and error-prone. Here's the interface for simple Person class:
// Person.h
@interface Person : NSObject

@property (strong) Address *address;
@property (strong) NSDate *birthdate;
@property (copy) NSString *firstName;
@property (copy) NSString *lastName;

@end

And here's the Address class used by Person:
// Address.h
@interface Address : NSObject

@property (copy, nonatomic) NSString *street;
@property (copy, nonatomic) NSString *city;
@property (copy, nonatomic) NSString *state;
@property (copy, nonatomic) NSString *country;
@property (copy, nonatomic) NSString *postalCode;

@end

If we have an NSArray of Person objects, we may want to sort them in country, lastName, firstName order. Here's one way to do that, using a comparator block:
// sort Person objects by lastName, firstName
Person *frodo = [Person new];
[frodo setFirstName:@"Frodo"];
[frodo setLastName:@"Baggins"];
// ...
[[frodo address] setCountry:@"Shire"];

Person *bilbo = [Person new];
[bilbo setFirstName:@"Bilbo"];
[bilbo setLastName:@"Baggins"];
// ...
[[bilbo address] setCountry:@"Shire"];

Person *legolas = [Person new];
[legolas setFirstName:@"Legolas"];
[legolas setLastName:@"Greenleaf"];
// ...
[[legolas address] setCountry:@"Mirkwood"];

NSArray *people = [NSArray arrayWithObjects:frodo, bilbo, legolas, nil];
NSArray *sortedPeople = [people sortedArrayUsingComparator:^(id item1, id item2) {
Person *person1 = item1;
Person *person2 = item2;

// NSComparisonResult is a typedef for int
NSComparisonResult result = [[[person1 address] country] compare:[[person2 address] lastName]];
if (result) {
return result;
}

result = [[person1 lastName] compare:[person2 lastName]];
if (result) {
return result;
}

result = [[person1 firstName] compare:[person2 firstName]];
if (result) {
return result;
}

return NSOrderedSame; // NSOrderedSame == 0
}];
// sortedPeople contains:
// Legolas Greenleaf (Mirkwood)
// Bilbo Baggins (Shire)
// Frodo Baggins (Shire)

The general pattern of a multi-field comparator is simple: check each field in turn, stop and return the comparison result if non-zero; if all fields are equal, return zero (or NSOrderedSame to be more descriptive). This quickly becomes tedious when you have many fields to sort by or you need to dig down into child or grandchild objects for fields.

Fortunately, there's an easier way to do this. NSArray has a method called -sortedArrayUsingDescriptors: that takes an array of NSSortDescriptor objects. Each NSSortDescriptor specifies a key path and sort direction (ascending or descending). The order of NSSortDescriptors in the array determines the precedence of each field. If you're not familiar with Key Value Coding (KVC), you may not have encountered key paths before. KVC is similar reflection in Java and other dynamic languages. KVC allows you to get and set fields on an object using the field names as strings, called keys. To access fields on child objects, you use keys separated by dots to form a key path; KVC knows how to drill down your object graph and access fields on child objects. There are a lot of interesting things you can do with KVC, but today we will stick to building an array of NSSortDescriptors:
NSSortDescriptor *byCountry = [NSSortDescriptor sortDescriptorWithKey:@"address.country" 
ascending:YES];
NSSortDescriptor *byLastName = [NSSortDescriptor sortDescriptorWithKey:@"lastName"
ascending:YES];
NSSortDescriptor *byFirstName = [NSSortDescriptor sortDescriptorWithKey:@"firstName"
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:byCountry, byLastName, byFirstName, nil];

Notice that the byCountry sort descriptor uses the key path @"address.country": it will first get the value of the address property of the Person object, then get the country property of the address. Key paths can be as deep as your object graph.

Using the array of sort descriptors is easy:
NSArray *sortedPeople = [people sortedArrayUsingDescriptors:sortDescriptors];
// sortedPeople contains:
// Legolas Greenleaf (Mirkwood)
// Bilbo Baggins (Shire)
// Frodo Baggins (Shire)

This certainly makes creating complex sort criteria much easier, and you're not limited to the default comparator for a field. You can specify a selector for a comparator method on the field this way:
// specify a method to call on the lastName object
NSSortDescriptor *byLastName = [NSSortDescriptor sortDescriptorWithKey:@"lastName"
ascending:YES
selector:@selector(caseInsensitiveCompare:)];

Or for more specialized comparisons, you can pass in a NSComparator block this way:
// sort descriptor using length of last name
NSSortDescriptor *byLastNameLength = [NSSortDescriptor sortDescriptorWithKey:@"lastName"
ascending:YES
comparator:^(id item1, id item2) {
NSString *lastName1 = item1;
NSString *lastName2 = item2;
// cast result to NSComparisonResult so that the
// compiler infers the correct return type
return (NSComparisonResult) ([lastName1 length] - [lastName2 length]);
}];

Specifying complex sort orders with NSSortDescriptors is the type of higher level, declarative code that is easy to write, easy to read and easy to maintain, and in most cases you should consider using NSSortDescriptor rather than writing your own comparator methods, functions or blocks.

Next time, we will look at sorting NSMutableArrays in place, rather than producing a sorted copy like the various -sortedArray methods.

Monday, December 5, 2011

iPhone owners upgrading to iOS 5 rapidly

Chart: OS is 'at least this' -- All devicesLess than two months after the release of iOS 5, nearly half of all iOS device owners have upgraded. Marco Arment, the developer of Instapaper (one of my favorite and frequently used apps), periodically releases iOS metrics he gathers from Instapaper users detailing the breakdown of iOS versions and iOS device types.

The tl;dr conclusion: nearly 99% of Instapaper users have iOS 4.0 or later, and nearly 95% have an iPhone 3GS-class processor or better. This jibes with what we see at Able Pear. We're planning to only support iOS 4.0 and later for all future app releases.

This is one of the things that Apple really does right with iOS. iPhone, iPad and iPod touch users upgrade their devices pretty rapidly; with iOS 5 allowing you to upgrade the OS directly on the device without connecting to iTunes, this will become that much easier and adoption of the latest OS versions will only improve in the future. As an app developer, there are pluses and minuses to Apple's tight control, but as an iOS user, this is a very solid plus -- upgrades are easy and developers rapidly support the latest iOS goodies rather than target some very old lowest common denominator OS version.

Check out the complete breakdown in More iOS device and OS version stats from Instapaper.

Wednesday, November 30, 2011

Great Geek Gift: Making Embedded Systems

Making Embedded SystemsIf you're looking for a great gift idea for that geek in you life (or for yourself :-) and you're interested in computer hardware as well as software, check out Making Embedded Systems: Design Patterns for Great Software by Elecia White. I had the good fortune to work with Elecia on a project last year and she's a top notch engineer -- and now an O'Reilly author. In her new book Making Embedded Systems, Elecia covers everything you need to know to get started building and programming embedded devices: system architecture, reading data sheets, debugging hardware and software, IO and timers, handling interrupts, peripherals and power consumption. If you're part of the Maker Faire/Arduino/Circuit Cellar hardware hacking community, or interested in learning about it, I highly recommend you check it out! Like most O'Reilly books, it's available as a printed book or in various e-book formats that work great with Kindle and iPads.

Tuesday, November 29, 2011

Objective-C Tuesdays: sorting arrays

Good news everyone! Objective-C Tuesdays is back! We left off a few weeks ago talking about techniques for inserting and removing items in arrays. Today we will cover sorting C arrays as well as NSArrays and NSMutableArrays.

Sorting C arrays with qsort()
The C standard library includes only one built-in way to sort C arrays: the qsort() function. qsort() is an implementation of the quicksort algorithm, a good general purpose sorting algorithm. qsort() sorts an array in place.

The qsort() prototype looks like this:
qsort(void *array, size_t itemCount, size_t itemSize,
int (*comparator)(void const *, void const *));

If you're not experienced using function pointers in C, the declaration of qsort() will look confusing. That's because declaring a C function pointer type is confusing. I'll use a typedef to make things easier to understand:
// alternate declaration of qsort using a typedef:
typedef int (*Comparator)(void const *, void const *);

qsort(void *array, size_t itemCount, size_t itemSize,
Comparator comparator);

Function pointers are declared in the same way that functions are declared in C, except they have a * before the function name like other pointer variables do. But there's one hitch. In a function pointer declaration, the * is ambiguous; by default, C will assume the * is part of the return type of the function. So when you declare a function pointer, you need a set of parentheses around the * and the function name in order to clue in the compiler.
// declare a function returning a pointer to an int
int *returnAPointerToSomeInt(void);
// which is interpreted as:
// (int *)returnAPointerToSomeInt(void);

// declare a pointer to a function returning an int
int (*returnSomeInt)(void);

Now that we've cleared that up, let's look at the declaration of qsort() again.
typedef int (*Comparator)(void const *, void const *);

qsort(void *array, size_t itemCount, size_t itemSize,
Comparator comparator);

The first three parameters of qsort() specify the array to sort, the count of items in the array and the size (in bytes) of a single item. Note that the array is of type void *, which allows us to pass any type of C array into qsort().

The last parameter is the comparator function.
typedef int (*Comparator)(void const *item1, void const *item2);

The comparator takes pointers to two items from the array and returns a negative number if item1 belongs before item2, a positive number if item1 belongs after item2 and zero if the two items are equal (or have equivalent ordering). This style of comparator function is used in many languages for sorting. I think of the items positioned on a number line when trying to understand a comparator:

item1 <=====<< item2
<-+------+-----+------+------+->
-2 -1 0 1 2

item2 >>=====> item1
<-+------+-----+------+------+->
-2 -1 0 1 2

When item1 belongs before item2, the comparator function will return a negative number; when item1 belongs after item2, the comparator returns a positive number. This relationship is the difference between item1 and item2, or item1 - item2.

The C standard library doesn't include many comparator functions, but they're easy to write. Here's an example of a comparator for ints to sort them in natural order:
int compareInts(void const *item1, void const *item2) {
int const *int1 = item1;
int const *int2 = item2;
return *int1 - *int2;
}

We create local variables int1 and int2 since a void pointer will automatically convert to a typed pointer in C, and we know that qsort() will actually be giving us pointers to ints. The two parameters are also const, so we can't modify the int values that the items point to (which would cause qsort() to go haywire). Then we can simply return the difference between the two int values to determine their sort order. We could do this in one line using casts and parentheses:
int compareInts(void const *item1, void const *item2) {
return *( (int const *) item1) - *( (int const *) item2);
}

Either way, now we can use our compareInts() function to sort an array of ints:
int array[6] = { 42, 17, 57, 19, 11, 5 };

qsort(array, 6, sizeof(int), compareInts);
// array now contains 5, 11, 17, 19, 42, 57

Now suppose we wanted to sort our array in reverse order? We would still use qsort() to do the job, but employ a different comparator function. Here is compareIntsReversed():
int compareIntsReversed(void const *item1, void const *item2) {
int const *int1 = item1;
int const *int2 = item2;
return -(*int1 - *int2);
// or simply return *int2 - *int1;
}

By reversing the sign of the comparator's return value, you can reverse the order of sorting.
int array[6] = { 42, 17, 57, 19, 11, 5 };

qsort(array, 6, sizeof(int), compareIntsReversed);
// array now contains 57, 42, 19, 17, 11, 5

The qsort() function is very flexible. You can sort arrays of complex types as easily as arrays of ints. To sort an array of C strings in lexicographic order, use the strcmp() function from the C standard library.
char const *array[3] = { "red", "green", "blue" };

qsort(array, 3, sizeof(char const *), strcmp);
// array now contains "blue", "green", "red"

Sorting an array of CGPoints, first write a comparator:
int compareCGPoints(void const *item1, void const *item2) {
struct CGPoint const *point1 = item1;
struct CGPoint const *point2 = item2;

if (point1->x < point2->x) {
return -1;
} else if (point1->x > point2->x) {
return 1;
}

if (point1->y < point2->y) {
return -1;
} else if (point1->y > point2->y) {
return 1;
}

return 0;
}

Notice that we first compare the X coordinates of the points and only check the Y coordinates if the X coordinates are equal. This is a common pattern when sorting over multiple fields in a struct. Here's an example of the CGPoint comparator in action:
struct CGPoint pointArray[4] = {
{ 4.0f, 3.0f },
{ 2.0f, 1.0f },
{ 4.0f, 1.0f },
{ 2.0f, 3.0f }
};
qsort(pointArray, 4, sizeof(struct CGPoint), compareCGPoints);
// pointArray now contains:
// { 2.0f, 1.0f }
// { 2.0f, 3.0f }
// { 4.0f, 1.0f }
// { 4.0f, 3.0f }


Other C sorting functions
For most common sorting jobs, qsort() it a reasonable choice, and it's the only choice that's included in the C standard library. OS X and iOS also include a couple of other sorting functions worth mentioning: heapsort() and mergesort(), which have the same parameters as qsort() and are detailed on the qsort() man page. heapsort() is slower than qsort() but uses a limited amount of memory while sorting, whereas qsort() uses recursion and can potentially overflow the stack when sorting huge arrays. mergesort() can be significantly faster than qsort() when the array is mostly in sorted order already, but is significantly slower when the array is in random order.

Sorting an NSArray
Objective-C provides a number of ways to sort an NSArray. Because NSArray objects are immutable, all the sorting methods on NSArray return a new sorted NSArray object and leave the original one unchanged. The most basic sorting method is -sortedArrayUsingFunction:context:, which is similar to sorting a C array with qsort(). The full method declaration looks like this:
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator 
context:(void *)context

The first parameter is a pointer to a comparator function. As we did for qsort(), I'll rewrite the method declaration using a typedef for the function pointer to make it a little easier to read:
typedef NSInteger (*Comparator)(id item1, id item2, void *context);

- (NSArray *)sortedArrayUsingFunction:(Comparator)comparator
context:(void *)context

The comparator function for NSArray sorting has a few differences from the qsort() one. It returns an NSInteger, which is simply a typedef for int. Instead of two items of type void const *, it takes two items of type id since NSArrays can only hold object types. And finally, there's an extra context parameter, a void pointer that allows you to pass extra information to the comparator if you need to (but you can safely ignore it if you don't need it).

Let's write a comparator function that orders NSStrings by their length.
static NSInteger compareStringsByLength(id item1, id item2, void *context) {
return [item1 length] - [item2 length];
}

Since we can send any message to a variable of type id, we don't even need casts or intermediate variables here. (Of course, we'll get a runtime error if we put the wrong type of objects into our array, but comparators for qsort() have the similar problems.)

And now let's see it in action:
NSArray *array = [NSArray arrayWithObjects:@"Florida", 
@"Texas", @"Mississippi", @"Delaware", nil];

NSArray *sortedArray = [array sortedArrayUsingFunction:compareStringsByLength
context:NULL];
// sortedArray contains:
// @"Texas"
// @"Florida"
// @"Delaware"
// @"Mississippi"

Now let's use the context parameter to make it easy to switch between normal and reversed sort order. We can pass a pointer to any kind of data we want, so we will use a pointer to a BOOL, where a YES value means reversed and a NO value means normal ordering.
NSInteger compareStringsByLength(id item1, id item2, void *context) {
BOOL *reversed = context;
NSInteger order = [item1 length] - [item2 length];
if (*reversed) {
return -order;
} else {
return order;
}
}

Now we need to pass something to the context parameter when we call -sortedArrayUsingFunction:context:
NSArray *array = [NSArray arrayWithObjects:@"Florida", 
@"Texas", @"Mississippi", @"Delaware", nil];

BOOL reversed = YES;
NSArray *sortedArray = [array sortedArrayUsingFunction:compareStringsByLength
context:&reversed];
// sortedArray contains:
// @"Mississippi"
// @"Delaware"
// @"Florida"
// @"Texas"

Note that we use the & operator to pass the address of the reversed variable as the context.

If you target iOS 3.2, OS X 10.6 or later, you can use the block version, -sortedArrayUsingComparator:. Blocks make one-off comparator functions easier to read and understand by putting the comparator definition right along side the sort method call. We can rewrite our example this way:
NSArray *array = [NSArray arrayWithObjects:@"Florida", 
@"Texas", @"Mississippi", @"Delaware", nil];

BOOL reversed = YES;
NSArray *sortedArray = [array sortedArrayUsingComparator:^(id item1, id item2) {
NSInteger order = [item1 length] - [item2 length];
if (reversed) {
return -order;
} else {
return order;
}
}];
// sortedArray contains:
// @"Mississippi"
// @"Delaware"
// @"Florida"
// @"Texas"

Since a block copies the value of variables like reversed in the enclosing scope at the time it's created, there's no need for a second context parameter to -sortedArrayUsingComparator:. Blocks are really handy, but if you find yourself writing the same comparator block in multiple places in your code, you might be better off using a plain old comparator function and -sortedArrayUsingFunction: instead to prevent duplicate code, in keeping with the DRY principle. (Or you might consider how to restructure your code so that sorting is defined in only one place.)

Since items in an NSArray are all objects, very often the items themselves have a useful comparator method. When this is the case, the -sortedArrayUsingSelector: method is very handy. NSArrays of NSStrings are very common, as is the need to sort in a case-insensitive manner. Using NSString's -caseInsensitiveCompare: method, we can sort this way:
NSArray *tagNames = [NSArray arrayWithObjects:@"H1", 
@"body", @"A", @"Head", nil];

NSArray *sortedTagNames = [tagNames sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
// sortedTagNames contains:
// @"A"
// @"body"
// @"H1"
// @"Head"

There's one more interesting way to sort an NSArray: we'll look at the -sortedArrayUsingDescriptors: method and the NSSortDescriptor class next week.

Wednesday, October 5, 2011

Steve Jobs


I lived in Palo Alto for many years, and would see Steve Jobs around town from time to time. I'd see him buying flowers at Stanford Florist, shopping for organic lentils in Whole Foods, talking on his iPhone outside Evvia before meeting people for dinner or strolling with his wife past Fraiche on a sunny afternoon.

And I've followed his career from the beginning, starting when I was a nerdy kid into computers. I read all about the Lisa, Steve's first baby, named after his daughter and now long forgotten and I followed the launch of its more successful sibling, the Macintosh. I was not fortunate enough to be a Mac owner in those early days but some of my friends had them and I always loved the little Mac toasters. I was primarily a Windows user for many years, but there was always something about the design of the Mac that was so clean and appealing, even years after Steve was forced out of Apple.

I was in college when he started NeXT. The black NeXT cube was so cool, so fascinating. While I had hoped that NeXT would be successful, unfortunately for too many people, myself included, the NeXT was too different, too expensive, my existing software and hardware wasn't compatible. Computing in the late 80's was very different, and the network effect of Wintel hardware and software compatibility drove even die hard Mac fans to buy PCs.

NeXT struggled. I was sad when they ceased producing that sleek black cube. They concentrated on selling the NeXTStep OS and development tools, with limited success at best. I wonder what it must have been like to have been so successful with Apple then to struggle so much with NeXT.

These years were also a struggle for Apple. Their biggest challenge was simply persisting in the face of the Windows juggernaut, but many of Apple's problems were self-inflicted. A decade of building atop Steve's original Macintosh foundation had left Apple with the OS equivalent of a house of cards. Apple recognized this, but their various projects to produce a new Macintosh OS never amounted to anything and their attempt to build a new class of product, the Newton, was overly expensive, marginally useful and widely lampooned.

I owned one of the first Newtons. I used it for about a year as my address book and calendar, but eventually gave it up in frustration and went back to a paper daily planner. It was a sad time for fans of Apple.

Then Apple acquired NeXT. NeXT had a modern operating system that nobody much wanted, and Apple made computers that needed a modern OS. And Steve came back to Apple as an advisor. And suddenly Apple didn't look so doomed. If you have the time, I recommend you watch Steve's Q&A session at WWDC 1997. It's his first WWDC after coming back to Apple. What comes through to me is that Steve clearly loves this stuff, and that he has his sights clearly focused on creating the best experience for the Mac user, not on some cool technology or selling more boxes to IT managers or making developer's lives easier. If you watch the Q&A, you'll see some discussion about OpenDoc and that it was killed. OpenDoc was a compound document technology that was supposed to compete with Microsoft's OLE. But OpenDoc was complex, buggy and late and one of the first things Steve did on returning to Apple was kill it. This was a big deal to Macintosh developers who had spent a lot of time and effort rewriting their apps to support OpenDoc, but Steve clearly saw that it didn't matter: most Mac users didn't care how their documents were stored, and that OpenDoc didn't bring those users much benefit. I think it's that keen sense, that focus on the user that served Steve so well in his career, but especially during his second tenure at Apple.

The history of Steve's second coming is now legend. But let's not minimize the audacity of Apple's most successful products. The iPod seemed a pretty random sideline for a computer company like Apple. Year after year, model after model, Apple relentlessly improved the iPod. After the disappointing Newton, I hadn't owned another Apple product until the iPod. It was a kind of gateway drug to Apple gear. A shiny 13 inch titanium MacBook Pro followed a couple years later. It was a secondary computer for traveling, but I began to use it more and more and my Windows machine less and less.

When the first iPhone was announced, I was initially lukewarm. Certainly a bold, audacious move by Apple, but it didn't grab me immediately. With so much buzz and enthusiasm building before the launch I went to Apple's site to take a look at the iPhone product info. After watching the iPhone demo video, slickly produced in the best Apple style, I came around and found myself in the Palo Alto Apple Store on launch day a couple of weeks later.

In my career writing software, I've always gotten the most satisfaction out of producing things that help people in their daily lives. I can only imagine how it must feel to be the leader of a team that produces such a revolutionary product loved by so many. Steve must have been insanely proud.

Industry and media pundits love to cast things as a contest: Windows versus Mac, Android versus iPhone, but to his credit and our delight, Steve Jobs could see past that. His final creation, the iPad, is so beloved by so many people, most especially by "your mom", those ordinary people for whom computers hold no intrinsic fascination. I think it's truly Steve's ultimate creation.

Yet remember that the iPad is only a year and a half old. We all know his health has been challenging, but it seems too soon to lose Steve. There's yet so much more to do, so many delightful machines to create. We will look to the folks at Apple to finish what he started.

Steve did what he loved up until the very end. If only we all could be that lucky.

Wednesday, August 31, 2011

"Where can we take the customer?"

And, one of the things I’ve always found is that you’ve got to start with the customer experience and work backwards for the technology. You can’t start with the technology and try to figure out where you’re going to try to sell it. And I made this mistake probably more than anybody else in this room. And I got the scar tissue to prove it. And I know that it’s the case.

...

And as we have tried to come up with a strategy and a vision for Apple, it started with “What incredible benefits can we give to the customer? Where can we take the customer?” Not starting with “Let’s sit down with the engineers and figure out what awesome technology we have and then how are we going to market that?” And I think that’s the right path to take.

- Steve Jobs at WWDC 1997

 

Wednesday, August 3, 2011

Developing on Android vs iOS

If you're building mobile apps these days, you're probably watching the Android market closely if you're not already developing for it. With reports coming in weekly that Android activations are growing faster than ever, simple extrapolation will tell you that soon, there will be more Android devices on that planet than people. Many successful mobile devs, most of them currently focused on Apple's iOS platform, are seriously investigating the Android platform and starting to port their apps. A few adventurous developers have written some thoughtful articles describing their experience and comparing Android and iOS development.

Nick Farina of Spotlight Mobile describes his impressions of Android garnered while porting his Meridian app from iOS. He covers the good and the bad of each platform in technical detail, and it's a good read if you're a developer moving from iOS to Android or vice versa. Nick approaches Android with the open mind of a developer who has worked on many platforms—the first version of Meridian was launched on Windows Mobile. Nick sums up his philosophy:
We decided it was important to keep the native stuff native, and to respect each platform’s conventions as much as possible.
...
So, we rolled up our sleeves, downloaded the Android SDK, and got to work
Back in March, Geoffrey Goetz of GigaOM gave his comparison of development on the two platforms. Goetz gives a high level summary, including a somewhat shallow summary table highlighting the platform differences. This is probably most useful if you're an executive who manages mobile developers, but is worth a quick read if you're a developer who's new to one of the two platforms. Goetz mentions Apple's WWDC videos and the Stanford iOS development course on iTunesU as a big plus for the developer learning experience on iOS and I have to agree: both are excellent resources. Goetz fails to mention that videos of many Google IO sessions covering Android are also freely available, though I can't say if they have the same high quality as Apple's iTunesU offerings.

Samuel Sutch gives another iOS developer's perspective on Android in a post on Google+. He sums up his take on Android in the opening paragraph:
The Android API requires it's users be really good programmers. Android abstractions are much more in-depth, (drawn out, forced, and complicated) than the equivalent iOS abstractions. However "Intents" are great once you get them.
I also recommend the discussion of the post on Hacker News.

Finally, if you're thinking about jumping on the Android bandwagon, keep in mind Ben Duchac's post, Why My Mom Bought an Android, Returned It, and Got an iPhone. Android can be a challenging experience for non-technophiles. I suspect that because Apple has positioned the iPhone and iPad as premium devices, they've captured a large fraction of consumers who are interested and engaged in their mobile experience, and iOS app sales have benefitted from that. Conversely, non-techie Android owners are less interested in using their devices to the fullest and more sensitive to price.

If you want to make money on app sales, I wouldn't bet the farm on Android right now. If you're targeting a technophilic audience, you probably want to be on both Android and iOS. If you're pursuing app sales to a mass market, I would recommend iOS first and Android as an optional second right now. However, if you have an existing product or service with a supplemental mobile app, you should definitely be planning to offer it on both iOS and Android.