Apr 27

The UITableView class is a wonder of efficient memory management, if you use it correctly.

Here’s the standard template code that Xcode generates when you create a subclass of UITableViewController:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Set up the cell...

    return cell;
}

The keys here are the CellIdentifier variable and the call to dequeueReusableCellWithIdentifier, which enable the iPhone OS to reuse existing instances of UITableViewCell whenever possible.

(Don’t create a unique reuse identifier for each row as I’ve seen some developers do. Yes, it’s much easier to deal with asynchronous download of images for each row if you know how to uniquely identify the cell, and you know that the cell is still in memory. But that totally defeats the efficient memory management that UITableView is capable of.)

Under normal circumstances a UITableView will create one instance of a UITableViewCell per row that is visible on the screen. As you scroll, the cell instance that just rolled off the screen will be reused for the cell that is about to appear.

To verify that this memory management is working as it should, add a log statement each time a new cell is created:

if (cell == nil) {
    DLog(@"creating a new cell");
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

When you run your app and start scrolling your table view, you should not see any creation of cells beyond the initial list (plus one). If you see “creating a new cell” log statements scrolling off the screen as you scroll the table view, you’ve got a problem.

If you just follow the standard Xcode template above, you should be fine. However if you’re loading a Nib for a custom table view cell layout using Apple’s recommended way, there’s an important detail you must not forget. (Tip of the hat to Jeff LaMarche for inspiring this blog post.)

Here’s the typical NIB loading code from Apple:

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        DLog(@"creating a new cell");

        // Load the table view cell from a Nib file.
        [[NSBundle mainBundle] loadNibNamed:@"CheckedTableViewCell" owner:self options:nil];

        // The checkedTableViewCell property is just a temporary placeholder for loading the Nib.
        cell = checkedTableViewCell;

        // We don't need this anymore, so set to nil.
        self.checkedTableViewCell = nil;
    }

    return cell;
}

The key here is that the CellIdentifier value must also be entered into Interface Builder, like this:

UITableViewCell-Identifier.png

If you don’t do this, then UITableViewCells will not be reused. (A telltale sign of this is that you’ll see lots of “creating a new cell” log messages.) There is no compiler or runtime warning if you fail to enter this critical piece of information into Interface Builder. So that log statement can be a useful warning.

(BTW, if you’re wondering what DLog is, then see this post: The Evolution of a Replacement for NSLog.)

written by Nick \\ tags: , , , ,

Apr 23

Boycott Gizmodo

We all enjoy reading the latest rumors about upcoming Apple products and play the guessing game of what Steve will unveil next. But this week Gizmodo went over the line. (If you have been immersed in coding this past week, here’s an excellent recap.) By their actions Gizmodo have caused great harm to an Apple engineer who made an unfortunate mistake. And they seem to take great pride in this.

The Apple engineer is one of us. He probably works 100-hour weeks building the gadgets we love to use and which we ultimately make our living from.

Therefore I encourage you to follow Craig Hockenberry’s advice and boycott Gizmodo. Since it’s clear that the only thing they care about is page views, let us all deprive them of the same.

Mac & the iPad, History Repeats Itself

An excellent article by Bruce Tognazzini (Apple employee #66) on Apple’s design process that leads to great products like the Mac, the iPhone and the iPad.

Increase iPhone App Downloads by A/B Testing App Names

A very smart technique for testing and finding the most effective name and icon for your app.

Core Data Tutorial: How To Use NSFetchedResultsController

If you haven’t looked at Core Data for your apps yet, you should. This article is the third part in a series, and deals with NSFetchedResultsController. This controller is by itself one of the best arguments for using Core Data in an iPhone app. (Although beware of this gotcha.)

How To Integrate Google Analytics Tracking Into Your Apps In 7 Minutes

I’ve written about Google Analytics for iPhone apps before. This is a nice tutorial with screen images. (Although given the recent change to paragraph 3.3.9 in the iPhone Developer Agreement, you may want to hold off on adding analytics to your app.)

written by Nick

Apr 14

Unfortunately my schedule will not allow me to attend the Voices That Matter – iPhone Developer’s Conference in Seattle, April 24-25. Therefore I will give my ticket away to a reader of this blog.

Just write a comment to this blog post stating why you want to go to the conference, and I will pick one entry as the lucky winner. My selection criteria will be as secret as Apple’s App Store approval process, and my decision is likewise dictatorial. :-) But since the conference is coming up soon, speed is of the essence.

Be sure to provide contact information in your comment so that I and the conference organizers can contact you. Your contact information will not be published.

Update: The lucky winner of the free ticket is John Depue. Congratulations! And feel free to write a guest post for the blog on what you learned at the conference…

written by Nick \\ tags:

Apr 12

I’m happy that I was wrong in my prediction about the first round of apps crashing due to memory issues. At least for the most part.

Although it seems that many developers had their apps rejected because they did not work very well when tested on real device, compared to running in the simulator. I think a large portion of these issues can be attributed to memory, or lack thereof.

It is now confirmed that the iPad only has the same amount of memory as the iPhone 3GS: 256 MB. Why couldn’t Apple spend a few dollars extra on a $500 device to double the memory to 512 MB? I think one answer can be found in iFixit’s teardown of the A4 processor. The memory is actually built-in to the same package as the A4 CPU. This makes for blazing fast access to the memory by the CPU, which is important when moving around large blocks of memory quickly for displaying on the screen. Having the memory chips physically close to the CPU also reduces the power consumption significantly. But cramming in the memory chips into the CPU “chip” limits the amount of memory you can have. It’s not like you can just add a standard SIMM module with more memory.

All hardware design is an exercise in trade-offs. For the iPad Apple had to find the best trade-off between:

  • Memory capacity
  • Memory access speed
  • Battery life

In their infinite wisdom, Apple settled on 256 MB of RAM for the first iPads. And we developers have to learn how to live within those constraints.

written by Nick \\ tags:

Apr 05

Now that you have had a chance to experience the iPad for a weekend it’s easier to understand why Apple has been so anxious to get this new device into people’s hands. I think the touch interface on the iPad is a leap similar to when we went from text based interfaces to a GUI. Never before have you been interacting so directly with an application or with data. With the traditional mouse + mouse pointer GUI there’s a significant level of indirection: drag a puck around on your desk and something moves in a similar pattern on the screen in front of your face. If you’ve watched a person learning to use a mouse for the first time you know what I mean. Not to mention the whole mess of single-click vs. double-click and left mouse button vs. right mouse button.

Where the iPhone touch interface felt more like a solution to the problem of cramming in many buttons on a small device, the iPad seems like the device for which the touch interface was really designed. (Maybe there is something to the theories that the tablet form factor was designed first and then shrunk down to the phone size.)

Interacting with the iPad is a very immersive experience. Understanding this will be key to creating successful iPad apps.

Here are some of the initial iPad apps that I’ve enjoyed, along with the UI design lessons that I learned from each.

iBooks

This is of course one of Apple’s showcase apps. You probably remember the “oohs and aahs” from the audience when Steve Jobs showed the page turn animation. In reality I find that animation to be irritating to watch each time I turn the page of a long book. Something that looks great on stage once or twice may not work as well when repeated 200 times. In your own apps having eye candy like this is great as a wow factor and gives your customers something to show off to their friends. But I would make it a setting so that it can be turned off for more concentrated and low key reading.

I wish Apple would have spent more time on making the book layouts more visually appealing. Paragraphs that have a large initial letter (often the case at the beginning of chapters) get an extra large line spacing between the first and second line. All lines are full justified, which looks great from a distance (i.e. on stage) but gets annoying when you’re actually reading the book and some of the words have very large spaces between them. You can switch between portrait and landscape mode, but when you do this the book is laid out for a different page size with the result that the page you were reading in portrait mode is not the page you’ll see in landscape mode. (A similar re-layout happens when you change the font of the book.)

I have not tried a Kindle device, so I don’t know if that reading experience is any better. But the Kindle iPad app has some of the same quirks as iBooks.

Lesson for developers: Obsess over the details. Especially those that your customers will experience every day with your app.

Mail

Apple’s Mail app is of course nicely done. One thing I don’t like is the large number of taps (4) required to navigate from one inbox to another inbox. Using a UISplitViewController to migrate an app from the iPhone to the iPad is a relatively quick solution, and kudos to Apple for providing this. But after you’ve done your quick iPad conversion, then take a step back and look at the overall navigation of your app. Are there ways you can make better use of the larger iPad screen? Do you have excessive navigation within a SplitViewController? How many taps does it take to navigate from one section of your app to another?

New York Times – Editor’s Choice

The NYT have gone for a traditional newspaper look for their app. I think design this makes sense for a traditional newspaper that is fighting to keep their print edition alive. At the same time it makes good use of the functionality of an electronic device in quickly linking from an intro to the full article, and the ability to show slideshows of photos and videos.

UI design lesson: It’s often a good idea to model your user interface after something in the real-world that is already familiar to your potential customers. Still, I’m curious to see what apps will come out in the future from organizations that are not encumbered by a tradition in paper media.

Zinio

Zinio is a magazine reader app. It’s a universal app that works on both the iPad and on the iPhone. It’s actually one of my favorite iPad apps so far, but I’m biased on this one because I was part of the team that developed the app. Given the limitations that Zinio has in that their product is in large part based on actual paper magazines, I think the app does a good job of replicating that experience on the larger iPad screen.

I’m too close to this app to give any developer lessons or advice. Please check out the app and let me know what you think in the comments.

Epicurios

Is the iPad finally the computer that will replace your recipe books in your kitchen? I gave the Epicurios app a thorough test with Easter dinner. The app has a very intuitive user interface, which pretty much follows the standard iPad productivity app layout. It’s uncluttered and has large text that you can read at a distance. As you’re cooking there’s a little orange marker arrow that you move along so you know where you are in the recipe. Unfortunately the touch screen doesn’t mix very well with maple syrup and melted chocolate

Games

I’m not a gamer, but I enjoy a few casual games that are easy to learn and provide quick entertainment for short bursts of time. Two games that really shine on the iPad are Harbor Master and Labyrinth. What struck me about these games is that it’s actually fun to watch someone else play. With the iPhone the screen is so small that it’s difficult for anyone but the player to see what’s happening. But with the iPad you can place the device on a table between you and you can both enjoy the game. I think this will be huge.

I also like how apps like Scrabble are making creative use of multiple devices. If you have an iPhone or iPod Touch you can view your rack of letters on your personal device, away from prying eyes. At least initially, there’s going to be a huge overlap between iPad and iPhone/iPod Touch owners.

Multitasking

Several iPad reviewers have of course lamented the lack or multitasking for third party apps. I think the lack thereof is a great feature. If you’re going to have an immersive experience you need to be focused on a single task.

There are several valid use cases for running a third party app in the background on a mobile device like the iPhone (i.e. tracking your current location) that probably don’t apply to a less mobile device like the iPad. There are other use cases that I think are better solved by “multi-devicing”. You want to listen to Pandora music while you’re working on your iPad – launch Pandora on your iPhone that’s in your pocket anyway. Want to keep an eye on your Twitter stream? The iPhone is fully capable of displaying 140 character messages and replying in kind. Etc.

Future

How will the iPad be used? What is the killer app? I think it’s way too early to predict how a device like the iPad will be used. Especially if you have not used one for an extended period of time.

I would encourage you to really use the iPad as a consumer would use it. Take off your developer hat for the moment. Don’t think about how you can best transfer your existing iPhone apps to the iPad. Do you find yourself lugging around your iPad everywhere you go just to check email or perform some other task? Or is the iPad mostly stationary, laying on the coffee table? What tasks do you prefer to do on the iPad vs. your iPhone or laptop? I think truly understanding these use cases will be key to developing apps that work great on the iPad.

written by Nick \\ tags:

Apr 01

For the past couple of weeks we’ve been fortunate to have access to two iPads. Per the rules, they’ve been tightly locked away in a secure, windowless room that we affectionately have come to know as the dungeon.

One day — this was before Apple had posted more detailed tech specs on their web site — one of the iPads fell on the floor. Gasp! A quick examination showed no cracks in the screen. Relief! But something was definitely amiss. The screen no longer rotated to match the orientation of the device. Our first thought was that the accelerometer had broken, and we irrationally started thinking about how to explain this incident to Apple. “You know those two super top-secret devices that you were gracious enough to loan to us… Well something happened to one of them…” [duck, cover, insert earplugs]

Shortly thereafter one of us noticed this small button on the right side of the iPad. “I wonder what this does?” Of course it turned out to be the screen rotation lock button, and once flipped back, the “broken accelerometer” started working again. :)

So after surviving this near-death experience, we decided to go for broke. What else could we do with these devices? Video out is an interesting feature if you’re using the iPad to make a presentation. But we’re not PowerPoint guys, we’re developers. And as a developer you know you can’t have enough screen real estate when you’re working. The latest iMacs have this cool DisplayPort input feature whereby you can use the iMac screen as a monitor. Hook two 27″ iMacs together this way, place them side by side and you have a pretty decent development environment. (Granted, downgrading a full iMac computer to be used as a monitor might be seen as a waste of money. But it’s all about esthetics. Having two identical looking monitors side by side on your desk is just more zen.)

Would the iPad have a similar feature? Apple is known for building in secret features and capabilities into their products. And since we didn’t have any tech specs or even a manual to explain trivial things like the screen rotation lock button, there was only one way to find out. After hooking the two devices together, it took some trial and error to get the right startup sequence (turn on the master first, then the slave display). But it worked!

You’ve probably seen Microsoft’s concept pictures and videos of their Courier tablet, which has a two-screen clamshell design. Of course Apple had to one-up them with a dual display setup for the iPad.

If you had a difficult time transitioning your apps from the good old 320 x 480 “fixed” display size to the larger iPad screen, then just try to wrap your head around a dual 768 x 1024 display. No more 4:1 pixel ratio. And if that’s not enough, imagine one of the displays in portrait mode and the other in landscape mode. How does your app cope with that? As you probably know by now, the iPhone OS does not give you much support in handling different interface orientations or different screen sizes. Each app has to deal with that in its own way. But there seems to be a new framework that may offer some help today. In the Private Frameworks directory, checkout the new ITSaprIlfoOLsdAy.framework.

Update: Sometimes reality is stranger than fiction. It has just come to my attention that there is an app for the iPad that extends your OS X desktop onto the iPad, effectively making it a second screen. The app is called iDisplay. But before you rush to install it you might want to checkout this review.

written by Nick \\ tags: ,

Mar 27

Developing apps for the iPad using the simulator is great. Assuming you have a decent Mac development environment the simulator is super fast and has seemingly unlimited amounts of memory. What more could you ask for?

Actually it would be much better if the simulator environment was closer to the device when it comes to speed and memory limitations. Especially memory.

Apple has never published how much RAM memory there is in any of the iPhone or iPod Touch devices in the past. And of course no such details are available for the iPad. You might assume that for a larger device there would be more memory available. Guess again.

The gorgeous 768 x 1024 display is begging to be filled with full screen images. Keep in mind that an image of that size will take up approximately 3 MB of precious memory. Keep 10-15 of them around in memory and you’re half-way to getting your app terminated because of memory usage.

Today is the last day to submit iPad apps for consideration for the new iPad App Store. I predict that we’ll see quite a few apps crashing on opening day because developers have not been able to test their app’s memory usage on an actual device with real world memory limitations.

written by Nick \\ tags:

Mar 18

If your iPhone app needs to store or access a lot of data locally you should take a look at Core Data. It’s not a panacea, but I find that it’s particularly useful when you need to search a lot of data that may result in a very long list to present in a table view. For this use case the NSFetchedResultsController is your friend. It handles many of the nasty issues of memory management, ensuring that you have enough data in memory to populate the visible portion of the table view instead of loading the entire result set into memory at once.

Your code to perform a fetch using NSFetchedResultsController may look something like this:

NSPredicate *predicate =[NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
[self.fetchedResultsController.fetchRequest setPredicate:predicate];
NSError *error = nil;
[self.fetchedResultsController performFetch:&error];

If you’re using a UISearchDisplayController you may be tempted to call this code each time the user enters a new character in the search field. There may be obvious performance reasons why you cannot want to do this. If it takes a few seconds to perform each fetch after each character then it will make for very slow data entry that will frustrate the user.

But there’s a more subtle reason why this is a bad idea, which I recently ran into.

NSFetchedResultsController optionally caches results and the cache content may get out of sync if you just change the NSPredicate like the code above does. One way to get around this is to delete the cache before you set the new predicate:

[NSFetchedResultsController deleteCacheWithName:nil];
[self.fetchedResultsController.fetchRequest setPredicate:predicate];

I’ve seen the first code section in many Core Data code examples, but I’ve never seen anyone mention the need to delete the cache before you perform another fetch with a different predicate. Now it turns out that you don’t have to do this in the current iPhone SDK, because it “just happens to work” anyway. But this behavior may, or may not, change in an upcoming NDA-covered SDK release. Consider this an advance warning.

written by Nick \\ tags: , , ,

Mar 12

As consultants and developers for hire we often don’t get to put our name in a product we work on. Sometimes we are not even allowed to reference the client or even mention that we were even part of the development effort. That’s part of the job description, and I’m ok with that.

What’s not ok is when people try to take credit for work they didn’t do.

Recently I’ve been contacted by several companies trying to sell their iPhone development services to me. I’m not interested in outsourcing the core of my business to another company, but I sometimes play along just to hear their pitch. One of the first things I ask for is references. What apps, available on the App Store, have you developed?

Here’s how the conversation went with the Business Development Manager at a company called Mindfire Solutions:

- In the document with references that Alex Sharma sent me, you list an app called Curious George. Can you tell me what your company’s role was on this project?

- Full lifecycle development.

- Very interesting. What would you say if I told you that a colleague of mine developed this app?

- That is very strange because we developed that app.

- I’m looking at the source code for the app on my computer screen right now and I see my colleague’s name in the headers, but not yours.

- Uhmm. Please hold a minute, let me talk to my project manager. [Typing furiously, presumably in an IM window.] Actually, we just did some image work for that app.

- So not really any full lifecycle development?

- No. And actually we’re not really allowed to reference this client. Please do not talk to them about this. Is it ok if we sign an NDA now?

- Let me get this straight: You claim to have developed apps that you didn’t, you provide client references that are not really references, and you share client confidential information when soliciting new business. Did I miss anything?

- Uhmm.

- Good bye.

As a developer I get really upset when people claim that they have written code that they clearly had nothing to do with. But I’m not a spiteful person so I was going to let this go. That was until Mindfire Solutions called us a second time! This time it was a colleague of mine that took the call, and they launched into a similar sales pitch. This is how you end up on the iPhone Developer Wall of Shame.

The next story comes courtesy of Rupen Makhecha at Aston Designs. He claims his 11 programmers are “are sort of expert in IPhone”. When asked for references he sent over a list of iPhone apps that included Twitterific.

- Twitterific? Really?!

- No reply.

Repeated attempts to clarify their role in the development of Twitterific were met with silence. I assume that they realized that their bluff had been called and they were busy working their next lead — one that hopefully would not question their references.

How do these companies think they can get away with such blatant lies? My guess is that they don’t realize how small and tight the iPhone development community in the U.S. is. I’m probably not more than two or three degrees of separation away from any professional iPhone developer based in this country. So if I don’t directly know the developer of an app, chances are that I know somebody who does. Within a great community like this, it’s very easy to verify who actually developed an app.

I know I’m not alone in getting these solicitations. Please share your stories in the comments.

written by Nick

Feb 26

Even though we just received a foot of fresh powder snow, conference season is already here. Are there any conferences you should/must attend as an iPhone developer? The answer will of course depend on your personal situation. I don’t like to travel much, but I really enjoy meeting fellow developers and to put faces to blog signatures and Twitter handles. So here are some upcoming conferences where you might meet me.

Mobile World Congress

This conference took place in Barcelona February 15-18. We had one of our developers speaking there, and at least one of our clients was there too. This is mainly a business conference and the focus is not on the iPhone. Apple is not one of the exhibitors. Microsoft was there in big force showing off an early build of Windows Phone 7 Series (nice name!). Global telecom companies announced a planned Super App Store where the unstated goal is to take away some of the power from Apple. (Good luck with that.)

NSConference

Traditionally a Mac developer’s conference with some of the world’s best Mac developers as speakers. This year they added a day devoted to iPhone programming. The 2010 conference has already taken place and Jeff LaMarche has a nice write-up.

CTIA Wireless – March 23-25, 2010 – Las Vegas, NV

This is the U.S. counterpart to Mobile World Congress. It takes place in Las Vegas every year. Like MWC it’s primarily a business conference, but with more focus on the U.S. market.

Don’t expect to learn any new Cocoa Touch skills here. But if you need a tax deductible reason to go to Vegas, this might fit the bill. Or if you just want to speak your mind to the AT&T executives Ralph de la Vega and Randall Stephenson, they’ll be there.

360|iDev – April 11-14, 2010 – San Jose, CA

I was a speaker at 360|iDev in Denver last summer and I really enjoyed the conference. It’s a small and intimate conference where you really get a chance to interact with both speakers and attendees. Both attendees and speakers were top-notch, and I learned a lot as well as made valuable connections.

The early bird pricing is already sold out. But the regular cost for three jam-packed days of sessions is still very reasonable.

Unfortunately I will probably not be able to attend this conference. I’ve got a few iPad projects that need to be wrapped up right around that time.

Voices That Matter – iPhone Developer’s Conference – April 24-25 – Seattle, WA

I have not been to this conference before, but the speaker lineup looks really good. The first day has a whole track devoted to UI design. This is something that I’ve been deeply involved in recently when porting iPhone apps to the iPad. (”Porting” is probably the wrong word here. “Redesigning the user experience from scratch” is more accurate.) On the second day there are several sessions that I plan to attend: Cocoa Design Patterns, Memory Management, Performance Tuning and Effective Networking. You can’t learn enough about these topics, and the opportunity to learn from some of the best in the business can’t be passed up.

Early bird pricing is available through March 12. And if you use the discount code “PHBLOGS” you’ll save an additional $100.

Full disclosure: I’ve been offered a complimentary ticket to the conference. If my schedule does not allow me to go, I will give the ticket away to a lucky reader here on the blog.

written by Nick \\ tags: