Tuesday, September 22, 2009

More Housecleaning

Here's another category I found while cleaning out my dev folder. It's another bit of Quicktime code for Cocoa. This is a category on QTMovie that makes it easier to deal with standard movies (i.e. ones with one video track and any number of audio tracks).

This same category exists in the MovieStepper project, but that version won't compile for 64-bit Cocoa applications because Apple has removed access to the underlying Quicktime data structures like Track and Media. This version uses only QTKit objects to accomplish the same tasks, and thus will compile for both 32-bit and 64-bit applications.

QTMovie-Frame.h
//
// QTMovie-Frame.h
// MovieStepper
//
// These are methods designed to be used on movies that contain only
// sequential frame data, e.g. straight movies. These methods make
// the assumption that the framerate is constant and that each frame
// is displayed for the same length of time. Do not use these methods
// on movies that have tracks other than a single video track and
// some number of audio tracks.
//
// This code may be used freely in any project, commercial or otherwise
// without obligation. There is no attribution required, and no need
// to publish any code. The code is provided with absolutely no
// warranties of any sort.

#import <Cocoa/Cocoa.h>
#import <QTKit/QTKit.h>

@interface QTMovie(Frames)
- (long)numberOfFrames;
- (void)gotoFrameNumber:(long)frameNum;
- (long)currentFrameNumber;
- (int)displayFPS;
- (float)desiredFPS;
- (NSImage *)frameImageForFrame:(int)frameNumber;
- (NSSize)size;
@end



QTMovie.m
//
// QTMovie-Frame.m
// MovieStepper
//
// Copyright 2009 Jeff LaMarche. All rights reserved.
//
// This code may be used freely in any project, commercial or otherwise
// without obligation. There is no attribution required, and no need
// to publish any code. The code is provided with absolutely no
// warranties of any sort.
//
// This code has been updated to work in 64-bit mode where access to
// the underlying Quicktime Carbon structures has been removed.

#import "QTMovie-Frames.h"

@implementation QTMovie(Frames)
- (long)numberOfFrames
{
NSArray *tracks = [self tracksOfMediaType:QTMediaTypeVideo];

for (QTTrack *track in tracks)
{
QTMedia *media = [track media];
NSNumber *frames = [media attributeForKey:QTMediaSampleCountAttribute];
if (frames != nil)
return [frames longValue];
}


return -1L;
}

- (void)gotoFrameNumber:(long)frameNum
{
int frames = [self numberOfFrames];
double percentDone = (double)frameNum / (double) frames;
QTTime duration = [self duration];
QTTime newTime;
newTime.timeScale = duration.timeScale;
newTime.flags = duration.flags;
newTime.timeValue = duration.timeValue * percentDone;
[self setCurrentTime:newTime];
}

- (long)currentFrameNumber
{
QTTime now = [self currentTime];
QTTime duration = [self duration];

if (now.timeValue == 0 || duration.timeValue == 0)
return 0;

double percentDone = (double)now.timeValue / (double)duration.timeValue;
int frames = [self numberOfFrames];

return (int) ((double)frames * percentDone)+1;
}

- (Fixed)rawFPS
{
NSArray *tracks = [self tracksOfMediaType:QTMediaTypeVideo];

for (QTTrack *track in tracks)
{
QTMedia *media = [track media];
QTTime duration = [[media attributeForKey:QTMediaDurationAttribute] QTTimeValue];
long numFrames = [self numberOfFrames];
double frameRate = numFrames*(double)duration.timeScale/(double)duration.timeValue;
return X2Fix(frameRate);
}

return -1;
}

- (int)displayFPS
{
return FixRound([self rawFPS]);
}

- (float)desiredFPS
{
return FixedToFloat([self rawFPS]);
}

- (NSImage *)frameImageForFrame:(int)frameNumber
{
QTTime restoreTime = [self currentTime];
[self gotoFrameNumber:frameNumber];
NSImage *ret = [self currentFrameImage];
[self setCurrentTime:restoreTime];
return ret;
}

- (NSSize)size
{
return [[self attributeForKey:QTMovieNaturalSizeAttribute] sizeValue];
}


@end

Monday, September 21, 2009

MV Blackjack - More Dev Folder Housecleaning



Here is an Xcode project for a simple Blackjack program. This is another one that was developed as part of a writing assignment, but then ultimately not used. This shows how you can use Core Animation rather than OpenGL to create a simple game. The cards are "dealt" to both players using the animatable properties of the views, and the effect is quite nice considering how simple it is to implement.

Dice Poker - Another One from the Dev Folder


Here's another Xcode project from the dusty corners of my dev folder. This is a project I wrote for an article Dave and I were going to write, but we decided on a different application.

As usual, typical warnings about not being production-ready, yada yada.

A Look at Android Development

I stumbled across this article on Android development today, and it was a very interesting read. The author gave a very balanced look at the Android platform, saying what he thought was good and bad. It reads like a very honest assessment. I didn't detect any obvious spin.

The one area where I don't agree with the author is his statement on Android's Intent/Activity model. This post claims that Android is "a big step ahead of the current iPhone programming model", but I can't help but to be reminded of OpenDoc and CyberDog. This idea of getting "away from monolithic, isolated applications" is not new; it's been floating around at least since the 1990s. If you look at theoretical, rather than practical implementations, it probably goes back much further than that, even.

Yet, here we are in 2009 still using monolithic applications.

Oh, wait, no we aren't. Not really.

When I write an iPhone application, much of the functionality I'm using wasn't written by me and isn't part of my application. It's part of a framework that's already on the phone. I think time has shown that the content-focused (or, intent-focused, if you will) way of dividing up code is problematic at best. It's great in theory, but problematic in practice.

In the example in the blog posting, how do I know if that barcode application is installed? What do I do if it's not? This approach opens up a huge number of problems with testing, installation, and development that offset any of the gains you get from not having code duplicated. The problems of Intent/activity are even more pronounced on an open platform like Android where the user has a lot of flexibility in terms of how they configure it and what they install on it.

This concept also just doesn't really fit the mobile application model that well. The iPhone isn't a general-purpose computer, and neither is an Android phone. If you look at the general population of consumers using smart phones, the way they use the phone the vast majority of the time really doesn't lend itself to this concept at all. They use and expect small applications to serve a defined, finite purpose.

If you're building megalithic applications for a smart phone, you're (quite simply) doing it wrong, and if you're not, you're not going to get all that much benefit from Intent/Activity, and you are going to pay a price in added complexity in the development process and the install process, not to mention greatly increasing the likelihood of problems for your customers.

That's not to say that the iPhone couldn't use some improvement in the inter-application communication arena. We currently have the ability to register application URLs, but it's a one-way trip. I can launch a barcode application, but I can't tell the barcode program to send me anything back unless I control both applications. In reality, I'm not sure how big of a limitation this really is, however. Most of the time, we're not going to want to rely on another application's functionality to handle an important application task unless the other app is one we wrote and have control over. If that's the case, then we have access to the source code and can included the functionality in the app and make it self-contained, greatly reducing the chance that our customers will have problems and get mad at us.

More Desktop Code

Although my focus for the last 20 months has been the iPhone, I've tried to stay at least in touch with Cocoa for the Mac. As a result, I tend to start a lot of small projects designed to help me learn, re-learn, or brush up on some specific area of functionality. A lot of these projects just end up gathering dust on my hard drive and are never used in any kind of production application, so since I'm doing a little housecleaning, I thought I'd post some of these projects that might be useful to iPhone developers wanting to get into Mac development or for newer Mac developers.

I've written several Cocoa applications over the years that work with Quicktime, including Crimson FX, a simple rotoscoping and special effects application. Back when I wrote these, most of the Quicktime functionality had to be accessed through Carbon calls. Since then, there have been several major releases of Quicktime, and Cocoa has gained some very robust Quicktime support by way of QTKit.

To familiarize myself with Cocoa's current Quicktime functionality, I wrote a small application that loads in a Quicktime movie and allows you to step through it frame-by-frame or to scrub through the frames using a slider. There's also a custom view that displays a filmstrip timeline, similar to the way iMovie displays a timeline.



This is neither a full-featured, nor a production-ready application, but if you're interested in writing a Cocoa application that needs to do more with Quicktime than simply play a movie, you may find some of the code in here useful. In addition to the filmstrip view, there's also a category that adds several methods to QTMovie for dealing with the individual frames of a movie's video track.

You can find the project here. As always, there are no restrictions on the use of this code, and I welcome any improvements or bug fixes you might come up with.

Sunday, September 20, 2009

Some Desktop GL Goodies

No time for a tutorial or lengthy description, but I thought I'd quickly post a few Xcode projects I've got.

First is the OpenGL ES icosahedron project from way back in OpenGL ES from the Ground Up, Part 2, only ported to Cocoa for the Mac. This is the very first one, with no lighting. It does show how to set up OpenGL ES on the desktop, including toggling full-screen mode. You can also use the arrow keys to increase or decrease the rotation speed.

Second, I've taken Apple's very old NSOpenGLView Full Screen sample code, and updated it to use the modern approach that works nicely with multiple displays and multiple GPUs. You can find the updated Xcode project here.

Third, here's another version of NSOpenGLView Full Screen sample code that creates a dedicated full screen app that doesn't support a windowed mode.

Saturday, September 19, 2009

App Store Resource Center

If you're part of the iPhone SDK Program, you likely already now about this, but I think it's cool enough to warrant a post.

Apple has just opened the App Store Resource Center for Developers. I haven't had the opportunity to go through it exhaustively, but at first glance, it appears to a welcome and pretty awesome tool for third party application developers.

Wednesday, September 16, 2009

Persistence Pays Off

Here's a report that says Microsoft's Bing search engine has captured over 10% of the search market. That's pretty impressive, but when you take into account that Yahoo! search is also powered by Bing, that means the Bing search engine is actually handling 26.7% of search traffic. That's over a quarter of the search traffic being handled by a product that's only existed for four months.

Wow.

That's impressive, phenomenal growth, and Google should be just a little concerned. It'll be a while before Bing has a chance of knocking Google out of its number one position, but they certainly look like they are going to fight the good fight in search now. I bet this number continues to grow for a while, they look to have momentum and are getting almost exclusively good press.

There's no doubt that Bing's presentation is slick and the search engine is capable. It's going to be a lot of fun watching the competition between Google and Microsoft heat up. It will also be interesting to see if Microsoft can get more of their departments to find their groove the way Search has. Maybe they should consider transferring some of Bing's management team over to the Windows Mobile groups.

Multi Core Mobile Chip

It looks like the rumors of a multi-core mobile chip are actually well-founded. Boy, would something like this make for a jaw-dropping future iPhone model that would give us a real need for blocks and GCD.

from Bill Dudney

Monday, September 14, 2009

iPhone Dot Net

Here's another interesting project, which allows programming iPhone applications in C# using Mono. It's based on the open source Mono project, but is a commercial product.

I have such mixed feelings about projects like this one. On one hand, I have tremendous admiration and respect for the ingenuity and hard work that went into making this work. Yes, it definitely does lower one barrier to entry for a considerable number of people with solid .NET experience, but that's not necessarily a good thing.

Tools like this encourage people to become hammer developers, that is to say, developers who use and are comfortable with only one language and framework. I have a very strong belief that being a hammer developer is, to put it bluntly, bad. I'm a strong believer in the importance of cross-training. I think it's important to see multiple approaches to problems. To become a great programmer, you need to be exposed to the work of a lot of different great (and not-so-great) programmers, and not just ones working in a the same language and toolset as you. Good developers have both breadth and depth of knowledge to draw upon when solving problems.

Although C# has some similarities to Objective-C, C# derives from the Simula object model, like C++ and Java, meaning it's strongly typed and does a lot more at compile time than Objective-C. There's nothing wrong with strongly-typed, static languages, but in many cases, the Simula and Smalltalk models really do require the use of different design patterns to be used most effectively. These differences are not insurmountable; Apple, for example, ported WebObjects from Objective-C to Java several years back. But, there were definitely bumps in the road; some parts of WebObjects 5.0 were necessarily klugey to work around the fundamental difference in the two languages.

Now, before people jump on me, let me just readily admit that I'm biased here. I really like Objective-C and I do think it's the absolute best option for programming on the iPhone. I also fully realize that Objective-C seems like a weird beast when you first come to it, especially after spending a lot of time with languages like C++ and C#.

But I do honestly think that one mark of a good developer is choosing the right tool for the job even (or maybe especially) when it's not a tool you are comfortable with. Learning is good, people. Learning is good. Don't ever say you're too busy to learn a new language or framework. Learning is an investment in your future viability and employability. You can't afford to stop.

Now, obviously, there's more than one opinion on this. The developer of MonoTouch, Novell, has a very different take on it. They believe that C# is so much more efficient than Objective-C that they're kindly willing to sell you a $1,000 toolkit. You'll still need to be a member of the iPhone Dev program, and you'll also still need a Mac for development. So, while this may lower the knowledge barrier for .NET developers to create iPhone programs, it certainly doesn't lower the financial ones any.

More on Blocks

Joachim Bengtsson has a very nice post on using C Blocks, well worth the read, even though we don't have blocks on the iPhone yet.

Friday, September 11, 2009

Grand Central Dispatch is Open Source

I find this fascinating.

Apple has open-sourced libdispatch, better known to most people as Grand Central Dispatch.

Grand Central Dispatch is something that developers - at least those who attend WWDC - have known about for well over two years. It's not something that your typical computer user would get excited over, but from the perspective of a developer, it's a really exciting technology that allows you to leverage the power of all the processing units in a given machine relatively easily.

When I saw the GCD demo that Bertrand Serlet gave at WWDC 2008, I was blown away. I looked at it as a game changer for the long term. Until there's a huge breakthrough in chip technology, utilizing multiple cores and multiple processors is the way to improved performance and this looked like something that was going to launch them way ahead of everyone else.

I saw GCD as a huge competitive advantage for Apple. And now, they're giving it away under a fairly liberal open source license (the Apple Open Source license, a variant of theApache license). They not only proposed a new standard, they're giving away the underlying implementation that's been in development for probably three or more years. Though I haven't looked at it, from some of the sessions I attended this year, it sounded like getting this working was quite an engineering feet

I think it's awesome, but I'm honestly surprised by it. Strategically speaking, it's an odd move. I see the benefit to Apple for having the block notation and syntax be an open standard. I'm having some trouble seeing the strategic benefit to letting other people use this amazing technology for free. I have to think this will buy at least a tiny amount of good karma from the Open Source community. Maybe.

Thursday, September 10, 2009

3.1 OpenGL ES Template

I've had some questions about whether I was going to upgrade my OpenGL ES template any more. I probably will, but it won't be any time soon. I did want to just point out that the iPhone SDK 3.1 is now GM and I can point you to the excellent OpenGL ES Application template in 3.1. I haven't had time to use this template extensively, but it looks to be setup really well for supporting both OpenGL ES 1.1 and OpenGL ES 2.0, so you might want to upgrade if you haven't and check it out.

A Disappointment?

I came across an interesting little rant today about how yesterday's announcement was a "disappointment". I understand that a lot of people were expecting cameras in the iPod Touch, and are let down. But putting things into perspective, I do think the important upgrade to the iPod Touch happened - the move to 600mhz ARM 7 CPU and the PowerVR SGX GPU) happened even though it wasn't explicitly stated.

But here's the comment that I found weird:
The shocker for me was to see Apple putting a video camera onto the iPod Nano 5th gen along with a bigger LCD and FM Radio w/ live pause. I just don't see the point or appeal here. A video cam is much needed on the iPod Touch. But apparently, Mr. Jobs thinks of the iPod Touch only as a video gaming platform... whatever!

I'm not surprised that people are upset about no camera on the Touch. It was heavily rumored and would, without a doubt, be a nice addition. I don't disagree that it would have been great for that to have happened. Here are the two things I take issue with:
The shocker for me was to see Apple putting a video camera onto the iPod Nano 5th gen along with a bigger LCD and FM Radio w/ live pause. I just don't see the point or appeal here.

You don't see the appeal? Have you not heard about the Flip Mino and other mini digital video camcorders? They're selling like crazy. So, now you can get an iPod that's also a fully featured video camera for the same price as a Flip Mino? It's basically a buy-one-get-one-free deal. I think these things are going to sell like hotcakes this holiday season. I see shades of the iPod Mini in these things, only more so. I probably won't buy one - my iPhone meets my needs - but I definitely can see the appeal, especially at that price point.

The thing I really have a problem with is:
Mr. Jobs thinks of the iPod Touch only as a video gaming platform... whatever!

Apart from sounding like the sort of comment that an annoyed spoiled twelve-year old child would make, it's a huge leap to assume that the lack of a camera in the iPod Touch yesterday is due solely to Steve Jobs' personal belief in the Touch as a gaming device only. He's already gone on record saying the decision not to put a camera in was to keep the price down. Some people don't believe this, but I think it's at least part of the reason. Apple has been working hard to combat their (not entirely justified) reputation for selling overpriced hardware lately. They dropped their laptop prices across the boards at WWDC while making the whole line faster and better.

I suspect that there were also technical limitations of some kind involved with the decision. The fact is, those of us who don't work at the Mothership don't have any knowledge of the process Apple went through to get to the product announcements at the event yesterday. There could have been supply issues, there could have been technical limitations with the thinner iPod touch case, or they could legitimately have thought it wasn't worth the additional expense, and that adding a camera wouldn't move substantially more units. It could simply have been too much to re-engineer both to accommodate new chips and to add a camera in the time they had.

It's fine to be disappointed or to wish that Apple had done something different; who hasn't done that at some point? But oversimplifying a scenario that you know almost nothing about based only an adolescent assumption that Steve Jobs is some kind of simpleton who just doesn't see the big picture or the potential of the iPod Touch is ridiculous.

For me, personally (fanboy that I am), with Steve Jobs giving the presentation, it would have been very hard to come away feeling disappointed. But even if you're disappointed, please still try to act like a grown-up, okay?

Wednesday, September 9, 2009

Bill Bumgarner on +initialize

This is a must read for anyone who overrides +initialize. I'll be honest, I either didn't know about this behavior or forgot it worked this way.

More on Core Data

Here is a correction and clarification on the Core Data problem reported here.

It appears that mergedModelFromBundles: does, in fact, work correctly with versioned managed object models. The problem is that Xcode doesn't clear out the old, non-versioned model when you version your data model, so you end up with both the versioned .momd and the original .mom file in your bundle and it attempts to load both, which is what causes the conflict, not the different versions inside the .momd.

Doing a Clean All should fix the problem, however I've tested this a bit, and sometimes you have to uninstall the app or reset the simulator to fix it, though I haven't isolated why yet.

Personally, I'm going to stick with the solution in the previous post for the time being. By specifying the versioned file explicitly, this can't be a problem either in testing or for your users. If you prefer to use the default template version of managedObjectModel, then make sure you do a Clean All after versioning your data model.

Thanks to Jack Nutting for pointing me in the right direction on this.

9/9/09 Event

Apple just finished their special event. They announced new, faster, and bigger iPod Touches, colorful iPod Nanos with a video camera, a new generation of the tiny Shuffle, and iTunes 9 with a bunch of nice new features, and iPhone OS 3.1 (I probably missed a few things there, but those are the main ones).

But the big news for developers is that there are now over 50 million iPhone OS devices in existence. Admittedly, some have been decommissioned, but any way you look at it, that's a lot of devices for a platform that's only been around a little over two years.

The breakdown, according to Steve is that they've sold more than 30 million iPhones and over 20 million iPod Touches.

To put that in perspective, it's greater than the installed based of all Mac OS X devices. Installed base is always an estimate, but the estimates I've seen put the Mac installed base at between 30 and 40 million devices.

Yes, the app review process can be a pain. The seemingly arbitrary rejections suck when they happen, and the expected low price point can be problematic. But, there really isn't a close second. There isn't a viable alternative. There's no single place to reach this many mobile users this easily, even in those situations where it's not necessarily that easy.

Tuesday, September 8, 2009

Table View Cells in Interface Builder - the Apple Way™

When Dave and I originally wrote Beginning iPhone Development, the SDK was very much in beta, and a lot of the documentation was incomplete or completely lacking. Given that, I think we did a pretty good job trying to stick with Apple's "best practices" and at guessing at which techniques would later evolve into best practices. In a surprising number of places, we do it the Apple Way™, even though we weren't 100% sure what the Apple Way™ would be when we were writing the book.

We did well, but we didn't bat 1.000.

One place where we missed was in loading table view cells created in Interface Builder.

In the first edition of the book, we hardcoded the index of the cell. That was bad, because when 2.1 shipped, the structure of the array returned by NSBundle changed and our code broke. Whoops!

In the second edition, we changed it so that the code no longer uses a hard-coded index, but instead iterates over the returned array looking for an object of the right class (UITableViewCell). That was a much better approach and works fine.

Somebody at Apple thought of a better way. It's effing brilliant. So brilliant, in fact, that when I first encountered the documentation for it, it took me a while to figure out just what they were doing. Here's the example code from Apple's documentation:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = @"MyIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"TVCell" owner:self options:nil];
cell = tvCell;
self.tvCell = nil;
}

UILabel *label;
label = (UILabel *)[cell viewWithTag:1];
label.text = [NSString stringWithFormat:@"%d", indexPath.row];

label = (UILabel *)[cell viewWithTag:2];
label.text = [NSString stringWithFormat:@"%d", NUMBER_OF_ROWS - indexPath.row];

return cell;
}

This is what confused me at first:

    if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"TVCell" owner:self options:nil];
cell = tvCell;
self.tvCell = nil;
}

The method loadNibNamed:owner:options returns an NSArray with the contents of the nib, but this code completely ignores that array. It doesn't even capture it. Then, it goes on and blithely assigns some instance variable to another instance variable, and then sets the first instance variable to nil.

Apple's documentation isn't perfect, but usually, it's pretty damn good, so I was pretty sure this code was right, I just wasn't getting something. There was a piece of the puzzle missing.

So, I looked at tvCell, which was declared earlier, and saw that it was an IBOutlet.

“Curiouser and curiouser!” Cried Alice.

Then it dawned on me. The bundle loader automatically connects outlets made to File's Owner when it loads a nib file if the outlet is nil. Notice that when the nib is loaded, the code specifies self as the bundle's owner. So, since this controller class is the File's Owner, when we load the nib, the outlet will get connected to an object in the nib if the outlet with that name on File's Owner is connected to an object in the nib.

So, what's happening is, the cell is created in its own nib file. The File's Owner for that nib file is our table view controller where the code above resides. In the nib file, the tvCell outlet on File's Owner is connected to the custom cell that gets created.

So, after this line of code:
[[NSBundle mainBundle] loadNibNamed:@"TVCell" owner:self options:nil];

tvCellis automatically connected to the custom cell that was created by virtue of the outlet connection in the nib. There's no need to loop or worry about indices. The bundle loader just does it automatically. So, that custom cell is then assigned to cell which is the table view cell that this method returns to the table to display the contents of this row. After that, tvCell is set to nil so that the next time this method gets called, the bundle loader once again connects the outlet for us.

That's just brilliant. Kudos to whomever at Apple thought of it.

If you'd like to see it in action, here's an Xcode project that uses this technique.

Menlo

By request, the code samples on my blog will now appear in the Menlo font if that font is installed on your system.

Core Data Migration Problems?

More iPhone 3 Development is going to have a brief discussion of migrations. We're going to use automatic migrations between chapters when we add to or change the data model. We're not going to do be discussing the more complex manual migrations, as Apple covers that topic pretty well in Core Data Model Versioning and Data Migration Programming Guide.

Working on the book, I discovered that there is a real gotcha in using migrations with Core Data on the iPhone. So far as I can tell, the way that you need to change your project for migrations isn't documented anywhere. It may be in there somewhere, but it certainly doesn't jump out at you.

After you create the first new version of your data model, the first thing you have to do (if using automatic migrations) is enable the automatic migrations in your persistent store coordinator. This step actually is documented, and it involves just creating an NSDictionary and passing it in when you create your persistent store coordinator. The modifications to the accessor method that was created for you automatically in your application delegate are in bold below:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}


NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"Foo.sqlite"]];

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil
]
;

NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {

NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}


return persistentStoreCoordinator;
}

From reading the documentation, it looks like that's all you have to do. Since you're done, you dutifully fire up your application and get…
Can't merge models with two different entities named 'Foo'
Well, Frack.

Here's what's going on. The .xcdatamodel classes don't get copied into your application bundle as-is. Instead, each one gets compiled into a new file of type .mom (managed object model). When you add a new version to your project, the current version gets compiled into a .mom file in your application's bundle in the Resources folder. It doesn't stop there, thought. It also creates a folder (technically, a bundle) in Resources named after your data model but with a .momd extension. Inside the .momd bundle, it puts a compiled .mom file for each of the other versions of your data model. This is understandable. It needs this information to do the automatic migration.

Here's the problem, though. The default managedObjectModel accessor method that gets created on your application delegate creates a managed object model using a factory method called mergedModelFromBundles:. This method iterates through all the files in your application's bundle looking for all .mom. It iterates the directory structure, even going down into folders and bundles. Here's what the method looks like as created for you:

- (NSManagedObjectModel *)managedObjectModel {

if (managedObjectModel != nil) {
return managedObjectModel;
}


managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];
return managedObjectModel;
}

The managedObjectModel hmethod is completely unaware of the fact that a .momd folder contains older versions of the same data model, and so it attempts to merge every version of your data model into a single merged model. Since different versions of the same data model typically have the same entities, the merge fails and you get an error message similar to the one above because entities must be unique. You can't have too "foo" entities in a single data model.

Here's the step that seems to have been missed in the documentation1. If you want to use migrations, you have to manually create your data model from the .momd bundles. Yep, can create a data model by providing a path to the .momd bundle instead of to a .mom file, and that's what you should be doing if you're going to use versioning. Here's what the new version might look like if you've got a single data model:

- (NSManagedObjectModel *)managedObjectModel {

if (managedObjectModel != nil) {
return managedObjectModel;
}


NSString *path = [[NSBundle mainBundle] pathForResource:@"Foo" ofType:@"momd"];
NSURL *momURL = [NSURL fileURLWithPath:path];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];

return managedObjectModel;
}

NSManagedObjectModel requires a URL to manually specify the location of a file, so we first get the path from NSBundle, then use it to create a file URL, then use that to load the data model file.

With this new version in place, automatic migrations should work, and you should be set up to do manual migrations based on the instructions in Apple's documentation.


1 - In Apple's defense, the documentation does say you can do this, it just doesn't make it clear that you need to.

Joy of Tech

I don't know if anybody noticed yesterday's Joy of Tech, but if you look closely in panels two and three, you can see the cover of Beginning iPhone 3 Development. In the lower-left right corner of both frames, there is clearly a black book with a grapefruit.

I think this counts as two of our fifteen minutes of fame.

Sunday, September 6, 2009

Backwards Compatible OpenGL ES 2.0

Here is an ambitious open source project intending to make OpenGL ES 2 code on the iPhone backward compatible. I haven't had time to check this out yet, but I plan to when I get some free time. It seems like this could be a godsend for developers facing the decision to use ES 1.1 or 2.0.

All the Little Lies

On my latest AT&T rant, I had a few people remark, basically, "who cares about MMS?".

The fact is, I don't. I have no plans whatsoever to use MMS. I'd like tethering, but I'm not willing to pay an additional charge to use it; I'm already paying for "unlimited data transfer" on my plan. I'm not exactly sure about the math involved, but I'm pretty certain that tethering won't cause me to use more than "unlimited" and it's not really AT&T's business just how I use that transferred data. Even when they do get it working, unless AT&T changes their policy with regards to tethering, I'll just forego it.

But, my earlier rant wasn't really about MMS. It wasn't about AT&T missing a deadline by two days. Hell, I've missed deadlines by two days before; I'm behind schedule on More iPhone 3 Development (which is why I'm sitting at my desk on a Sunday morning). At its core, my rant was s about something bigger.

It's about AT&T's approach to interacting with their customers. It's about the way they treat us and the complete lack of respect they show for us. AT&T has no qualms about flat out lying to their customers. They have a pattern of never taking any responsibility for problems their customers have, even ones that can't possibly be anybody else's fault but theirs. If you talk to customer service, it's like they all took a course in Defensive Talking as part of their employee training.

Here's just one little example. I logged on to AT&T to pay my iPhone bill this morning. This is the message we all get when we log on to pay (you've probably seen it):


You can click on the image for a bigger version if it's too small to read, but it says:
Your login is being verified. Depending on your Internet connection speed, it may take a few minutes for this process to complete.

And it does take a fair length of time to login - much longer than any web site that I use on a regular basis. But, that has nothing to do with my Internet speed, and the person who typed that message almost certainly knew that. I'm on a cable modem, and I paid this bill very early on a Sunday morning. Cable modems are shared bandwidth, so the less people online, the faster your service:



The transfer speed for pages, like AT&T's payment page that are mostly text, is meaningless when you're pulling down 12 megabits per second. Of the twenty seconds or so it took to log in, less than a second was due to my "Internet connection speed" Pinging that server resulted in a ~25ms round trip, which is 0.025 seconds. Worst case scenario, maybe a second or two was eaten up by transfer time and latency, or about a tenth of the time it took to log in.

AT&T obviously realized that logging in to their system would take longer than most users would expect it to take. Instead of fixing it, or just saying "hang on a second, we'll be right with you", they try to push the blame off of themselves and onto their customer and their customer's ISP. Believing, possibly rightly so, that most of their customers either wouldn't be savvy enough to realize that they were being lied to or just wouldn't care.

When it comes down to it, I don't hate AT&T because of their spotty coverage, failure to predict reasonable growth in 3G usage, or any of the other things that I've complained about here. Those are all just symptoms of a much bigger problem.

I hate AT&T because they seem to hate me (and you, too). At very least, they don't respect me, and they certainly don't take responsibility for their actions. We wouldn't accept this type of behavior from the real people in our lives. If I went to my publisher and told them I was behind on the book because of something my publisher did that was only tangentially related to my writing, they wouldn't believe me, and they'd be pissed off at me to boot.

Why don't we hold corporations like AT&T to that same standard we hold individual people? Why have we become so tolerant of abuse and disrespect from large corporations?

Saturday, September 5, 2009

Saving Tabs

I've been so ranty lately that I thought I should take a short break from writing More iPhone 3 Development to put up something technical. This is a relatively beginner-level tutorial, but it's one of those little features we take for granted but really hate when it's not there (at least I do).

I'm talking about saving the selected tab. When you start Apple's Clock application, for example, it always takes you to the tab you were on when you last used it. In most cases, this is a very good idea. There may be cases where a specific tab should have preference, but generally, you should bring the user back where they left off.

If you're using a tab bar controller, it's relatively simple to implement this. In viewDidLoad or applicationDidFinishLaunching:, you need to do something like this:

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger whichTab = [defaults integerForKey:kSelectedTabDefaultsKey];
tabBarController.selectedIndex = whichTab;

Then, either when the selection changes, or when the application quits, you have to store off the tab in the preferences so it'll be there next time. I prefer doing it whenever the tab selection changes because then we've captured it, even if there's a crash or phone call, but doing it when the application finishes is fine for most purposes. Here's how you reverse the process:

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger whichTab = tabBarController.selectedIndex;
[defaults setInteger:whichTab forKey:kSelectedTabDefaultsKey];

But what if you're just using a UITabBar and not a UITabBarController? That's a touch more difficult because tab bars don't work by indices. It's relatively easy to add the exact same functionality that's on the tab bar controller to the tab bar by using a category, however:

UITabBar-Index.h
#import <Foundation/Foundation.h>

@interface UITabBar(Index)
- (NSUInteger)selectedIndex;
- (void)setSelectedIndex:(NSUInteger)newIndex;
@end



UITabBar-Index.m
#import "UITabBar-Index.h"

@implementation UITabBar(Index)
- (NSUInteger)selectedIndex {
return [self.items indexOfObject:self.selectedItem];
}

- (void)setSelectedIndex:(NSUInteger)newIndex {
self.selectedItem = [self.items objectAtIndex:newIndex];
}

@end


Once you have that, you can import this category and use the exact same code from above on the tab bar rather than the tab bar controller.

Here's an example project. It includes a functioning tab bar application that saves the tab position, and also contains the category above.

Debugging Drawing

Apple has a nice little utility called QuartzDebug in /Developer/Applications/Graphics Tools, and one of the features of this program is that it will highlight all redrawing that gets done in every application. Every time a view is redrawn, it flashes. This is a great tool for determining if you're doing unnecessary drawing in your drawRect: method, or if you're somehow triggering unneeded redraws some other way.

I've had a lot of people ask me about doing this on the iPhone. I've been told by several people that they saw this functionality demonstrated at the iPhone tech talks, which had me stumped. I completely forgot that you can get very similar functionality by passing an argument called NSShowAllDrawing to your application on launch. This is mentioned in this excellent technote on debugging.

Michael Fey has a (somewhat holder) blog post, complete with video, that shows how to use NSShowAllDrawing. His example shows using it in a Cocoa application, but the process is exactly the same for using it in an iPhone application.

Update: A couple of people pointed out in the comments that this option is also available using Instruments. If you run with the Core Animation template, there's a checkbox labeled "Flash Updated Regions", which is checked in the screenshot below:



I haven't been able to get the Core Animation template to work for me on the Simulator, though. I'm not sure if that's by design, or a problem with my installation.

Friday, September 4, 2009

Apologism from AT&T

AT&T has posted a video on YouTube where their resident blogger, "Seth", claims to "take head on" our complaints as AT&T users.



The explanation sounds okay...

That is, if you don't actually let your brain function while "Seth" talks. The fact that AT&T conveniently left out of their explanation is that all that massive growth they've been seeing equates to massive growth in their monthly income. In other words, they had the resources, but they didn't plan well enough or spend enough of that massive gross income to actually provide the service all those people are paying $100 a month or more for. Their competitors in this country and all over the world somehow managed to do what AT&T didn't, and they try to make it sound like it's not AT&T's fault.

I can't speak for anyone else, but I don't find this video particularly satisfying or mollifying. In fact, to me, it looks like apologism of the worst sort. Don't make lame, after-the-fact excuses. Tell me when it's going to be better and say you're sorry for fucking up. Say you're sorry for taking gobs of cash from all of us each month and for not providing even halfway decent service much of the time.

Own up or don't bother talking. Don't tell us that by sending you all this money every month, we caused this problem. That's over-the-top ridiculous.

I don't put much faith in rumors, but I really do hope the ones about AT&T's exclusivity ending soon are true, because I'm about fed up with AT&T.

Sigh

Microsoft's marketing brain trust continues to look like a 40 year old with a combover trying to look cool at a high school dance.

C'mon Microsoft. You're not selling tupperware or cosmetics. Most sane people aren't going to celebrate a software release that they weren't directly involved in by inviting friends over and playing pin-the-tail-on-the-donkey. Even if you do manage to bribe some people with a free copy of Windows 7 and a chance at fabulous cash and prizes… well, the parties aren't going to look anything like this:


Sheesh. How can a company with so much money and so many smart people working there keep coming up with consistently moronic ideas?

That picture and the advertisement it's part of is a beautiful demonstration of what Jeff Atwood recently blogged about.

 
Design by Wordpress Theme | Bloggerized by Free Blogger Templates | coupon codes