Oct 10

Fancy UILabels

Craig Hockenberry’s battles with improving the scrolling performance of UITableView.

Cocoa for Scientists (Part XXVIII): Bonjour and How Do You Do?

A great article on low level networking: How do you find and talk to another iPhone or Mac?

iPhone Developer’s Cookbook, The: Building Applications with the iPhone SDK, Adobe Reader

Erica Sadun’s book is now published. It’s a very good read. My only complaint is that there’s more emphasis on private APIs then I’m comfortable with.

Sample code for the book is available here.

Update: The sample code contains a description on how to use the coverflow API hidden in the bowels of the iPhone. Apple has since rejected apps that use this private API.

The How and Why of Cocoa Initializers

While not specifically an iPhone topic, there has been a long ongoing controversy among Cocoa developers on how to properly write init methods. Bottom line is to follow Apple’s example. This article explains why.

written by Nick \\ tags: , , , ,

Oct 08

Creating objects can be very expensive in terms of performance. This is especially true for UIControls that are also added to a UIView. Instead create a number of objects once and reuse them when needed.

Here’s a code snippet from a book reader application that lays out each text paragraph as it’s own UILabel. Since each page has a varying number of paragraphs each with varying number of lines of text I initially created the necessary UILabels each time a page was rendered. Bad idea!

Now I have an array (often called an object pool) of UILabels that have been created and added to the page UIView. Initially the hidden property is set to YES for all these labels. When a page is rendered a UILabel is picked from the pool, initialized with the appropriate text, location and size. And the hidden property is set to NO to display the label.

// Add new text to existing labels
for (int i = 0; i < MAX_LABELS; i++) {
   UILabel *textLabel = [textLabels objectAtIndex:i];
   if (i < [currentPage.paragraphs count]) {
      NSString *paragraph = [currentPage.paragraphs objectAtIndex:i];
      CGSize textSize = [paragraph sizeWithFont:textFont
 						constrainedToSize:CGSizeMake(PARAGRAPH_WIDTH, 1000)
 						lineBreakMode:UILineBreakModeWordWrap];
      textLabel.font = textFont;
      textLabel.frame = CGRectMake(PARAGRAPH_LEFT_MARGIN, yOffset, PARAGRAPH_WIDTH, textSize.height);
      textLabel.hidden = NO;
      textLabel.text = paragraph;
      yOffset = yOffset + textSize.height + PARAGRAPH_SPACING;
   } else {
      textLabel.hidden = YES;
      textLabel.text = @"";
   }
}

 
In addition to speed performance improvements this solution also has the significant benefit of managing memory much better. 

written by Nick \\ tags: