i’m so full of ideas

Archive for the 'objective-c' category

iPhone: nibless

February 28, 2010 5:07 pm

I just had a look, and my blog is the number one hit on google for the search phrase “iphone nibless.” That leads to a blog post I wrote on the subject last year. I linked to another blog that explained how to accomplish such a goal, but that blog post has since been taken down. Hrmph. Okay, I guess I have to cover this subject again.

Generally speaking, Apple makes beautiful apps that are elegant and easy to use. Interface Builder is a glaring exception. I can’t stand that thing. So unbelievably complicated. I can’t ever find what I’m looking for.

If you’re writing Mac apps, I guess you’re stuck with it. Most Mac windows contain a lot of controls, and you need a way to design them. If you’re writing iPhone apps, it’s a net loss. Most iPhone views contain a single control that takes up the entire view area, so Interface Builder is an unnecessary complication. So I’m going to tell you how to make an iPhone app that does not require any nibs at all. I am using Xcode 3.2.1 on Snow Leopard, but these instructions will likely work for older versions as well.

1) Start Xcode. From the File menu, pick “New Project.” In the window that opens, select the iPhone OS Application category on the left. In the group on the right, pick “Window-based Application.” This may work fine for the other project templates, but I haven’t tested that. Create the new project, name it whatever you want.

2) Remove MainWindow.xib from the project and put it into the trash. It is no longer needed. (Yay!)

3) Edit the Info.plist for your project by double-clicking on it. It will have a name similar to projectname-Info.plist. The plist file will have a key named “Main nib file base name,” with the value MainWindow. Remove this key completely: select it, and press the Delete key. Save the file.

4) Xcode will have created an app delegate class for your project, named something like niblessAppDelegate. Yuck, what a horrible name. Rename this class to AppController, by directly editing the header and source files for the class. You can of course pick a different name, or even skip this step altogether, but I’m going to assume from here on out that your app delegate class is called AppController.

5) At this point, you have destroyed the mechanism that iPhone OS normally uses to recognize the name of your app delegate class, which it needs to know to load your app. Fortunately, there is an easy way around this: you must pass your app delegate’s class name to UIApplicationMain(). Xcode created a file called main.m that contains your app’s main() function. Edit it now, and change main() so that it looks like this:

int main(int argc, char *argv[]) {     NSAutoreleasePool*  pool = [[NSAutoreleasePool alloc] init];         int retVal = UIApplicationMain(argc, argv, nil, @"AppController");         [pool release];     pool = nil;         return retVal; }

That’s it, you’re done. You may continue modifying this project until you have a real application.

At this point, you might be thinking: Whoa, scary change. Is this really safe? Well, I can offer myself up as an example. I’ve submitted two of my own apps to the App Store that use this technique, both of which have been downloaded thousands of times. I’ve gotten hundreds of emails from users over various issues, but my apps not having nibs has never been a problem.

UIProgressHUD replacement

February 27, 2010 11:22 pm

Dear internet: I have been searching for a UIProgressHUD replacement for many, many months. Why have you failed me? I don’t suppose it was because of that other, similarly named UIProgressHUD replacement? Which I am not going to link to or name, because it sucks. Sorry, yes I am a jerk, but it does. If I have to explain to you why it’s a bad idea to make a progress view that’s launching background tasks, then there is no helping you.

UIProgressHUD

So, anyway. In case you’re new to this. UIKit has a nice control called UIProgressHUD for displaying a heads-up, semi-transparent view with a spinny-control on it, and a single line of text. It looks good, it works well, it’s easy. The only down side is that it’s undocumented, so you can’t use it in apps destined for the App Store.

I used UIProgressHUD in a project I was writing for a client a few months ago. This particular app was not destined for the App Store, so it seemed like a nice shortcut. Maybe that’s not such a hot idea, but they weren’t paying much, so I couldn’t justify a detour for writing a brand-new view. But now here I am again, needing the exact same thing for my card game, and google searches still only turn up that progress view that thinks it’s an app launcher. Hrmph. Time to write my own, I guess.

WBProgressHUD

My goal was to write an exact, drop-in replacement for that view I can’t use. I’ve included screenshots of Apple’s original view, and my clone view. Pretty darn close, don’t you think? The only real differences are details that I don’t want to change. For example, I think they picked a font size that’s a bit excessive.

It would be great if I could just paste the source file and header file right into this post, for your amusement. My view is mercifully short, and would lend itself to that. Alas, it requires several support modules, so I had to make it into an example Xcode project. I’ve developed a huge library of iPhone support code by this point, so it doesn’t make sense to duplicate things in every single view and controller I write.

One clever feature of my demo project: you can change one line of code and it will use either UIProgressHUD or my own WBProgressHUD. No other code has to change, because the two views are that similar, dawg. It makes for a good test bed for developing a clone view such as this one.

Download wbprogresshud.zip by clicking here. If you like this project, how about hiring me to write more stuff like it? My contact details are on my About page.

iPhone: UIImage rotation and scaling

January 31, 2010 8:03 pm

Hello to my three remaining blog subscribers! Long time no see!

For my first post back after my long hiatus, I’m going to revisit the single most popular entry I’ve written to date, which was about UIImage rotation. I’ve used that code a great deal since I first wrote it. I’ve modified it several times. It’s pretty near perfect at this point.

The original code I modified for that earlier post was for dealing with photos taken with the iPhone camera. I stripped out a lot of that stuff, because I was only interested in rotating images that were embedded in the program. And then, wouldn’t you know it, I got a contract job that required me to deal with iPhone camera images as well. So I had to revisit the subject.

The original code from blog.logichigh.com had the rotation and scaling all lumped together in one chaotic function. I split it out into separate rotation and scaling methods, so they can be used independently. It also makes for easier code maintenance.

The code contains [UIImage rotate:], which works the same as the last time around, but it has been streamlined a bit internally. It will rotate any UIImage to any orientation, with or without mirroring. Then we have two scaling methods, the simplest being [UIImage scaleWithMaxSize:]. You provide it with a float value, which is the largest width and/or height that you want the output image to have. If the input image is already smaller than that, it won’t be scaled.

Finally, the all-singing, all-dancing method for massaging photos from the iPhone camera: [UIImage rotateAndScaleFromCameraWithMaxSize:]. It examines the EXIF data in the image and, if needed, rotates it to the proper orientation. Then it scales the image to the maximum width and/or height supplied to the method.

This code has been thoroughly tested in several real-world iPhone projects. There are no known bugs. If you find one, I’d love to hear about it, so I can fix it.

Here’s the header file, WBImage.h:

// WBImage.h -- extra UIImage methods // by allen brunson  march 29 2009 #ifndef WBIMAGE_H #define WBIMAGE_H #import <UIKit/UIKit.h> @interface UIImage (WBImage) // rotate UIImage to any angle -(UIImage*)rotate:(UIImageOrientation)orient; // rotate and scale image from iphone camera -(UIImage*)rotateAndScaleFromCameraWithMaxSize:(CGFloat)maxSize; // scale this image to a given maximum width and height -(UIImage*)scaleWithMaxSize:(CGFloat)maxSize; -(UIImage*)scaleWithMaxSize:(CGFloat)maxSize  quality:(CGInterpolationQuality)quality; @end #endif  // WBIMAGE_H

And here’s the implementation file, WBImage.mm:

// WBImage.mm -- extra UIImage methods // by allen brunson  march 29 2009 #include "WBImage.h" static inline CGFloat degreesToRadians(CGFloat degrees) {     return M_PI * (degrees / 180.0); } static inline CGSize swapWidthAndHeight(CGSize size) {     CGFloat  swap = size.width;     size.width  = size.height;     size.height = swap;     return size; } @implementation UIImage (WBImage) // rotate an image to any 90-degree orientation, with or without mirroring. // original code by kevin lohman, heavily modified by yours truly. // http://blog.logichigh.com/2008/06/05/uiimage-fix/ -(UIImage*)rotate:(UIImageOrientation)orient {     CGRect             bnds = CGRectZero;     UIImage*           copy = nil;     CGContextRef       ctxt = nil;     CGRect             rect = CGRectZero;     CGAffineTransform  tran = CGAffineTransformIdentity;     bnds.size = self.size;     rect.size = self.size;     switch (orient)     {         case UIImageOrientationUp:         return self;         case UIImageOrientationUpMirrored:         tran = CGAffineTransformMakeTranslation(rect.size.width, 0.0);         tran = CGAffineTransformScale(tran, -1.0, 1.0);         break;         case UIImageOrientationDown:         tran = CGAffineTransformMakeTranslation(rect.size.width,          rect.size.height);         tran = CGAffineTransformRotate(tran, degreesToRadians(180.0));         break;         case UIImageOrientationDownMirrored:         tran = CGAffineTransformMakeTranslation(0.0, rect.size.height);         tran = CGAffineTransformScale(tran, 1.0, -1.0);         break;         case UIImageOrientationLeft:         bnds.size = swapWidthAndHeight(bnds.size);         tran = CGAffineTransformMakeTranslation(0.0, rect.size.width);         tran = CGAffineTransformRotate(tran, degreesToRadians(-90.0));         break;         case UIImageOrientationLeftMirrored:         bnds.size = swapWidthAndHeight(bnds.size);         tran = CGAffineTransformMakeTranslation(rect.size.height,          rect.size.width);         tran = CGAffineTransformScale(tran, -1.0, 1.0);         tran = CGAffineTransformRotate(tran, degreesToRadians(-90.0));         break;         case UIImageOrientationRight:         bnds.size = swapWidthAndHeight(bnds.size);         tran = CGAffineTransformMakeTranslation(rect.size.height, 0.0);         tran = CGAffineTransformRotate(tran, degreesToRadians(90.0));         break;         case UIImageOrientationRightMirrored:         bnds.size = swapWidthAndHeight(bnds.size);         tran = CGAffineTransformMakeScale(-1.0, 1.0);         tran = CGAffineTransformRotate(tran, degreesToRadians(90.0));         break;         default:         // orientation value supplied is invalid         assert(false);         return nil;     }     UIGraphicsBeginImageContext(bnds.size);     ctxt = UIGraphicsGetCurrentContext();     switch (orient)     {         case UIImageOrientationLeft:         case UIImageOrientationLeftMirrored:         case UIImageOrientationRight:         case UIImageOrientationRightMirrored:         CGContextScaleCTM(ctxt, -1.0, 1.0);         CGContextTranslateCTM(ctxt, -rect.size.height, 0.0);         break;         default:         CGContextScaleCTM(ctxt, 1.0, -1.0);         CGContextTranslateCTM(ctxt, 0.0, -rect.size.height);         break;     }     CGContextConcatCTM(ctxt, tran);     CGContextDrawImage(ctxt, rect, self.CGImage);     copy = UIGraphicsGetImageFromCurrentImageContext();     UIGraphicsEndImageContext();     return copy; } -(UIImage*)rotateAndScaleFromCameraWithMaxSize:(CGFloat)maxSize {     UIImage*  imag = self;     imag = [imag rotate:imag.imageOrientation];     imag = [imag scaleWithMaxSize:maxSize];     return imag; } -(UIImage*)scaleWithMaxSize:(CGFloat)maxSize {     return [self scaleWithMaxSize:maxSize quality:kCGInterpolationHigh]; } -(UIImage*)scaleWithMaxSize:(CGFloat)maxSize  quality:(CGInterpolationQuality)quality {     CGRect        bnds = CGRectZero;     UIImage*      copy = nil;     CGContextRef  ctxt = nil;     CGRect        orig = CGRectZero;     CGFloat       rtio = 0.0;     CGFloat       scal = 1.0;     bnds.size = self.size;     orig.size = self.size;     rtio = orig.size.width / orig.size.height;     if ((orig.size.width <= maxSize) && (orig.size.height <= maxSize))     {         return self;     }     if (rtio > 1.0)     {         bnds.size.width  = maxSize;         bnds.size.height = maxSize / rtio;     }     else     {         bnds.size.width  = maxSize * rtio;         bnds.size.height = maxSize;     }     UIGraphicsBeginImageContext(bnds.size);     ctxt = UIGraphicsGetCurrentContext();     scal = bnds.size.width / orig.size.width;     CGContextSetInterpolationQuality(ctxt, quality);     CGContextScaleCTM(ctxt, scal, -scal);     CGContextTranslateCTM(ctxt, 0.0, -orig.size.height);     CGContextDrawImage(ctxt, orig, self.CGImage);     copy = UIGraphicsGetImageFromCurrentImageContext();     UIGraphicsEndImageContext();     return copy; } @end

iPhone: keyboard trouble

August 28, 2009 3:07 am
It is possible to type into two or more of these fields at once without dismissing the keyboard

It is possible to type into two or more of these fields without dismissing the keyboard

A couple of months ago, a user of my card game reported a bug. He said that when he tried to change the names of all the robot players at once, only one of them actually changed. I tried to duplicate the problem, but couldn’t. For me, all three robot player names changed. I asked him for more details, but like many non-technical users, he wasn’t able to articulate the problem very well. He said he kept fiddling and fiddling and eventually got all three names changed. I had made a real effort to duplicate the bug and failed. So I wrote this one off as user error.

Over the next few weeks, the same bug got reported three more times. I was still not able to reproduce it. I asked for more specific instructions on how to tickle the bug, but none of this batch of people took the time to send a second email. I can’t blame them. Most people view it as a frivolous time-wasting diversion, useful for whiling away a few minutes while in line at the grocery or something.

Fortunately for me, the fifth report came from a fellow programmer. He provided very explicit instructions, and I was finally able to reproduce it. Now that I understand what was happening, it’s no small wonder that it evaded me for so long. The problem was that my mental model of how the iPhone accepts text input was wrong.

I had assumed the sequence of events was always like this:

• User touches an editable text field
• Keyboard rolls up into view
• User types some text
• User presses the return key on the keyboard
• Program forces the keyboard to disappear
• Program processes the new text

But guess what, here is another possible sequence of events:

• User touches an editable text input field
• Keyboard rolls up into view
• User types some text
User touches a second text input field
User edits the second input field
• User presses the return key on the keyboard
• Program forces the keyboard to disappear
• Program processes the new text

A third possible outcome is that the user navigates away from the current view to a different one, and therefore never presses the return key.

This sounds complicated, but it turns out that the fix is pretty easy. You simply have to treat “user pressed the return key” and “user finished editing” as two separate events, rather than conflating them as one.

The assumption here it that your users are typing into UITextField objects. The fix I’m proposing is for UITextField delegates, i.e., whatever object implements the UITextFieldDelegate protocol. Here’s an example implementation of one of those methods:

-(BOOL)textFieldShouldReturn:(UITextField*)textField {     [textField resignFirstResponder];     return TRUE; }

This is the delegate method that gets called when the return key is pressed. I used to process the newly-edited text field contents in here. That was a mistake which led to the bug I’m talking about. In a typical implementation of this method, the only thing you want to do is make the keyboard go away, which is what the [textField resignFirstResponder] line does.

Here’s the method you should implement to deal with new text field contents:

-(void)textFieldDidEndEditing:(UITextField*)textField {     // deal with new text field contents here }

I can’t show a typical implementation, because only you can decide what you should be doing with the new contents of the text field. But as far as I can tell, this method is always called when the user is finished editing the text field, regardless of why that happened. It could be because the return key was pressed, or because the user switched to a different text field, or because she switched away from the parent view altogether, or perhaps other reasons I’m not aware of.

NSLog() sucks

July 18, 2009 8:15 am

In a previous installment I explained why printf() sucks, and how I fixed it. Today I am going to focus on NSLog(), which sucks even worse.

Why NSLog() sucks

Here’s a typical NSLog() call:

  NSLog(@"hello: %d", 6);

Note that it doesn’t require a newline character at the end of the format string. So we’ve made a little progress over printf(). It’s not until you see the output that we get to what I think is wrong with it:

  2009-07-18 08:48:29.067 nslog_sucks[44201:10b] hello: 6

Sigh. Just as with printf(), NSLog() is optimized for a corner case I hardly ever need. The assumption is that I would always want to know when this action took place down to a thousandth of a second, and that I’d want to see the name of the program doing the output, the program’s PID, and so on. The output I’m interested in is drowned out by unimportant noise.

Replacing NSLog() with something better

This is how NSLog() is defined, in NSObjCRuntime.h:

  FOUNDATION_EXPORT void NSLog(NSString *format, ...)
   __attribute__((format(__NSString__, 1, 2)));

At first glance, it appears that this would give you the same sort of warning that you get with printf() if the format string doesn’t match the arguments supplied. Sadly, I’ve never been able to coax GCC into supplying warnings in that case. But I added the same __attribute__ decoration to my NSLog() replacement, in case this is just a bug in current versions of GCC that will be fixed at some point in the future.

Finally, here’s the source code for nlog(), my NSLog() replacement that doesn’t fill the screen with unnecessary details. The header file, nslog_sucks.h:

// nslog_sucks.h -- an NSLog() alternative // by allen brunson  july 18 2009 #ifndef NSLOG_SUCKS_H #define NSLOG_SUCKS_H #include <Foundation/Foundation.h> // nlog(), a better NSLog() void nlog(NSString* nfmt, ...) __attribute__((format(__NSString__, 1, 2))); #endif  // NSLOG_SUCKS_H

And the implementation file, nslog_sucks.m:

// nslog_sucks.m -- an NSLog() alternative // by allen brunson  july 18 2009 #include <stdio.h> #include <stdlib.h> #include <Foundation/Foundation.h> #include "nslog_sucks.h" void nlog(NSString* nfmt, ...) {     va_list    args = NULL;     NSString*  nstr = nil;         va_start(args, nfmt);     nstr = [[NSString alloc] initWithFormat:nfmt arguments:args];     va_end(args);         puts([nstr UTF8String]);         [nstr release];     nstr = nil; } int main(int argc, const char** argv) {     NSAutoreleasePool*  pool = [[NSAutoreleasePool alloc] init];     nlog(@"hello from nlog: %s %d", "text", 2);         [pool release];     pool = nil;         return 0; }

Drawing NSStrings in unusual rotations

June 1, 2009 8:10 pm

If you’re used to writing apps for desktop computers, the iPhone’s screen can seem awfully small. You must make creative use of every pixel available to you. One way to do that is to draw some text vertically, rather than horizontally, which I decided to do for an iPhone app I’m working on right now.

For drawing normal horizontal text, UIKit has a category called UIStringDrawing that provides convenient methods for drawing the contents of an NSString to the current graphics context, like drawAtPoint:withFont: and drawInRect:withFont:. Sadly, UIKit does not provide methods for drawing text in any other orientation except standard horizontal. I will now present an NSString category you can add to your own iPhone projects that allows you to draw vertical text from bottom to top, top to bottom, or horizontal text upside down.

My category supports the same three UITextAlignment options that UIKit provides for left, right, or centered text alignment. If using my drawInRect:... method to draw a string that’s too wide to fit within the rectangle supplied, the right end of the string will be truncated to fit, with an ellipsis character added.

UIKit does a better job of handling long strings than my code does. UIKit can wrap text to two or more lines, for example, which I did not try to emulate. The UIKit methods also allow you to provide a UILineBreakMode enum value, which gives you fine-grained control over how strings are truncated. I personally don’t need that much flexibility, so my category has no such support.

Finally, there is one last limitation of my category that might be a deal-breaker for you. The standard UIKit string-drawing functions can be used to display any Unicode character, so long as the font you’re using has a glyph for it. My category is limited to the roughly 255 characters present in the MacRoman character set. That means my code is good for displaying text in English and most European languages, like French and German, but it is completely unsuitable for text in, say, Chinese.

I’m aware that this is an outrageous limitation. You’d be hard-pressed to find a programmer who is more gung ho about Unicode than I am. I struggled mightily for several days trying to find a way around this. Sadly, this is due to the way that the underlying CoreGraphics drawing routines work, and there is no good way around it that I can see. I’ll cover this in more detail later, in case you’re interested.

Using the WBTextDrawing category

I’ve included a sample Xcode project that demonstrates the use of my WBTextDrawing category. Download the project by clicking here.

I’ve provided a screen-shot, but it isn’t much to look at. There are five strings displayed onscreen. The four strings at the edges of the view are displayed with my own WBTextDrawing category, drawn in all four available orientations. The string in the center is drawn with one of UIKit’s own drawInRect:... methods. The lines in red show the bounding rects used to draw the five strings. The four strings around the edges all have an associated green pixel, which illustrates the draw point used to draw that particular string. Naturally you wouldn’t draw the green and red bits in a real app. I added them to this demo so you’ll have a better idea of what’s going on.

Almost all the code in the project is boilerplate that can be safely ignored. To add my string-drawing category to your own program, copy WBTextDrawing.mm and WBTextDrawing.h out of this project and into your own. All other source files presented here are for demonstration purposes only.

You will note that WBTextDrawing.mm ends with an mm extension, rather than the usual m. That’s because this source file must be compiled as Objective-C++, due to the fact that it contains a small amount of C++. I know many Objective-C programmers have a strong aversion to C++, and believe me, I understand! But the underlying CoreGraphics method that’s used to draw rotated strings insists on being given a const char*. It does not work with NSString objects directly. So I chose to convert NSString objects to std::string objects just before drawing them. Yes, I could have accomplished this without leaving the confines of Objective-C, but std::string seems to me like the best tool for the job.

Specifying text drawing locations


UIKit’s UIStringDrawing category contains several drawAtPoint:... methods for drawing NSString objects. The point you pass to these methods is the far left end of the font’s baseline, as illustrated by the green point in the first figure. For the sake of compatibility, I chose to use this same convention for the drawAtPoint:... method in my own WBTextDrawing category. No matter what drawing orientation you’re using, the specified draw point is always the far left end of the font’s baseline, relative to the string being drawn. This is also the way the low-level CoreGraphics drawing routines work, conveniently enough. See the second figure for what this looks like when drawing a bottom-to-top vertical string.

UIStringDrawing also has several drawInRect:... methods. In this case, the rectangle supplied is the entire area allotted for drawing the string, illustrated by the red rectangles in figure one and figure two. Again, my own WBTextDrawing category does the exact same thing, for compatibility’s sake.

Text drawn is limited to MacRoman

This is without a doubt the worst limitation of my WBTextDrawing category. I see no good way around it, however.

Whatever method you use for drawing rotated text, you must accomplish two goals: 1) Apply a given font to the current drawing context, and 2) Draw the NSString supplied by the caller. The easiest way I can see to apply a font is to use CGContextSelectFont(). That method gives you two encoding options: kCGEncodingMacRoman, which uses the MacRoman encoding, or kCGEncodingFontSpecific, which means you must provide your own character-to-glyph translations, as far as I can tell. Ahem. UIKit can’t do this by itself, apparently, but the expectation is that us lowly app programmers should be able to do it? As if. So the only real option here is to use the MacRoman encoding, then use CGContextShowText() to display the text. This is the way my category works. Anything outside the MacRoman character set displays as gibberish.

There’s another method you can use to apply a font to the current context: CGContextSetFont(). This method doesn’t take any kind of encoding parameter at all, so it would appear to be immune from the problems presented by CGContextSelectFont(). Alas, once you’ve called that method, CGContextShowText() doesn’t work anymore. The CoreGraphics docs say you should instead call CGContextShowGlyphsAtPoint(). That function expects its caller to supply an array of glyphs, not characters. Which implies that you’ve got some method up your sleeve that will convert characters to glyphs for a given encoding. I don’t know about you, but I don’t have any such method lying around. So I’m stuck with boring old MacRoman.

This seems like an awfully strange limitation to build into the low-level CoreGraphics text drawing routines. If you know of any way around it, please tell me what it is, so I can update my text-drawing category appropriately.

cocoa: app memory usage

May 3, 2009 6:30 pm

My least favorite part of Cocoa programming is its reference-counted memory management scheme. If you can exclusively target Mac OS X 10.5 or later, then you can use garbage collection instead, which is better. But it doesn’t work on Mac OS X 10.4 or earlier or the iPhone, so garbage collection might as well not exist, as far as I’m concerned. Yes, I know Cocoa’s reference-counting scheme has “only a few simple rules” you have to follow … yet Apple’s own apps tend to leak pretty badly. Back when I was using Mac OS X 10.4, I could only run Safari for a few hours before I had to restart it. Seems to be less of a problem in Mac OS X 10.5, but they’re likely using garbage collection these days.

So, early versions of your Cocoa programs are probably going to leak. There are ways to combat this. The primary ones are the leaks command-line tool and the Instruments app that comes bundled with Xcode, neither of which I like very much. I’d prefer that the app itself report its bad behavior. To that end, I’d like my apps to be able to tell how much memory they are using.

Surprisingly, an app’s memory usage is subject to interpretation. Suppose your app and another are both using one in-memory copy of a shared framework. Should your app’s memory total include the size of the framework or not? What if your app has a lot of memory allocated that currently lives on disk in a swap file — should you count that?

I’ve spent some time in the past studying this issue, and I’ve decided to go with a figure called the “resident set size.” This is more-or-less how much memory your app is using. Not perfect, but plenty close enough for my needs. Here’s how you can get it.

#include <mach/mach_init.h> #include <mach/task.h> #include <sys/time.h> #include <sys/resource.h> #include <stdint.h> #include <string.h> #include <unistd.h> int64_t MemoryUsage() {     task_basic_info         info;     kern_return_t           rval = 0;     mach_port_t             task = mach_task_self();     mach_msg_type_number_t  tcnt = TASK_BASIC_INFO_COUNT;     task_info_t             tptr = (task_info_t) &info;         memset(&info, 0, sizeof(info));         rval = task_info(task, TASK_BASIC_INFO, tptr, &tcnt);     if (!(rval == KERN_SUCCESS)) return 0;         return info.resident_size; }

This was difficult to write. It makes use of Darwin kernel APIs, which Google knows almost nothing about.

This works on any version of Mac OS X back to about 10.2, I think. It also works on the iPhone simulator, as well as on actual iPhone hardware. I’ve tried it myself on all these, including my own phone. The fact that this function works unmodified on both Macs and live iPhone hardware is proof positive that the two platforms use very similar kernels.

If you want to use this to detect leaks, you have to track your apps’ memory usage over time. Take a snapshot of your app’s size near the beginning of a run, then put your app through its paces for half an hour or so. Is the app’s memory usage trending up?

In addition to being useful for tracking leaks, I simply appreciate knowing how much memory my apps are using. There’s a definite upper limit on how much RAM you can allocate on an iPhone, and there’s no virtual memory at all. If your iPhone app exhausts all physical memory, it can’t start swapping to disk, it’ll just get killed.

I’ve noticed that the app I’m working on now uses 14MB in the simulator, but only 8MB on real iPhone hardware. Probably because simulator apps are really just modified Mac apps. Windows, views, and other user interface elements on the Mac are no doubt heavier than their iPhone counterparts.

iphone: drawing rectangles

April 28, 2009 9:33 am

Mac/AppKit and iPhone/UIKit development are more alike than different. In general, I’d say the iPhone APIs feel more “fresh” than their Mac equivalents. It seems to me like the current crop of Cocoa engineers at Apple have learned a lot in the years since the company ditched “classic” MacOS for an updated version of NextStep, and they’ve used that wisdom to design this new crop of frameworks. And they’re not afraid to revisit past decisions that didn’t work out so well: they discarded MacOSX’s view-origin-in-the-lower-left-corner mistake and put it in the upper left corner for the iPhone, where it belongs.

On the other hand, AppKit is far more complete than UIKit. Almost anything user-interface-related you might want to do on the Mac is covered by APIs in AppKit. UIKit is missing many of those amenities, likely because it is targeted at resource-constrained devices that don’t have the space for dozens of multi-megabyte frameworks. The practical upshot is that I’ve spent a lot of time writing iPhone stuff that AppKit would have provided for me. All the more reason to write blog posts like this one, so coders can google up the answers rather than spending days reinventing wheels.

I like drawing rectangles. Only rarely do they end up in my final apps, but I use them a lot while debugging, to ensure that a view area I’ve staked out is where it should be. On the iPhone, this kind of thing is done with Core Graphics. It is a very complete framework. You can do anything with it. The down side is that CG code tends to be verbose and complicated, requiring lots of function calls to do the simplest things. This is a situation crying out for wrapper functions.

I’ve written a UIView category that provides methods for drawing just about any type of rectangle you can think of: filled or outlined, rounded corners or square, including point-drawing methods. You can provide a color to draw with, or use the current draw color, which is black, unless you change it. You can draw a translucent rectangle by specifying a draw color that has an alpha value of less than one. You can change the radius of the rounded corners drawn by fiddling with the constant kCornerSize at the top of the implementation file.

This is beginner-level stuff, so I guess I should add that UIKit doesn’t let you draw things whenever you feel like it. (That’s true for all GUI environments I’ve ever programmed for, now that I think about it.) You must draw only within a UIView’s drawRect: method. If this is news to you, you should read one of Apple’s introductory texts before continuing.

Here’s a sample drawRect: method you can add to an existing view to demonstrate the rect-drawing methods:

-(void)drawRect:(CGRect)rect {     CGRect  test = CGRectMake(0.0, 0.0, 20.0, 20.0);     [self strokeRect:test color:[UIColor magentaColor]];     test.origin.x += test.size.width;     [self strokeRoundRect:test color:[UIColor yellowColor]];     test.origin.x += test.size.width;     [self fillRect:test color:[UIColor blueColor]];     test.origin.x += test.size.width;     [self fillRoundRect:test color:[UIColor redColor]]; }

… which produces the output shown in the screen-shot. here’s the header file for the category:

// WBViewRect.h -- rectangle drawing methods for UIView // by allen brunson  march 2 2009 #ifndef WBVIEWRECT_H #define WBVIEWRECT_H #import <UIKit/UIKit.h> @interface UIView (WBViewRect) // save and restore graphics context -(void)contextRestore:(CGContextRef)context; -(CGContextRef)contextSave; // points -(void)drawPoint:(CGPoint)point; -(void)drawPoint:(CGPoint)point color:(UIColor*)color; // filled rects -(void)fillRect:(CGRect)rect; -(void)fillRect:(CGRect)rect color:(UIColor*)color; // filled rects with rounded corners -(void)fillRoundRect:(CGRect)rect; -(void)fillRoundRect:(CGRect)rect color:(UIColor*)color; // outlined rects -(void)strokeRect:(CGRect)rect; -(void)strokeRect:(CGRect)rect color:(UIColor*)color; // outlined rects with rounded corners -(void)strokeRoundRect:(CGRect)rect; -(void)strokeRoundRect:(CGRect)rect color:(UIColor*)color; @end #endif  // WBVIEWRECT_H

Finally, here’s the implementation file:

// WBViewRect.mm -- rectangle drawing methods for UIView // by allen brunson  march 2 2009 #include "WBViewRect.h" #pragma mark module data static const CGFloat kCornerSize = 5.0; static CGRect rectStrokeAdjust(CGRect rect) {     rect = CGRectIntegral(rect);     rect.origin.x    += 0.5;     rect.origin.y    += 0.5;     rect.size.width  -= 1.0;     rect.size.height -= 1.0;     return rect; } static void roundRect(CGContextRef context, CGRect rect,  CGFloat ovalWidth, CGFloat ovalHeight) {     CGFloat  fw = 0.0;     CGFloat  fh = 0.0;     assert(ovalWidth  >= 1.0);     assert(ovalHeight >= 1.0);     CGContextSaveGState(context);     CGContextTranslateCTM(context, CGRectGetMinX(rect), CGRectGetMinY(rect));     CGContextScaleCTM(context, ovalWidth, ovalHeight);     fw = rect.size.width  / ovalWidth;     fh = rect.size.height / ovalHeight;     CGContextMoveToPoint(context, fw, fh / 2.0);     CGContextAddArcToPoint(context, fw, fh, fw / 2.0, fh, 1.0);     CGContextAddArcToPoint(context, 0.0, fh, 0, fh / 2.0, 1.0);     CGContextAddArcToPoint(context, 0.0, 0.0, fw / 2.0, 0, 1.0);     CGContextAddArcToPoint(context, fw, 0.0, fw, fh / 2.0, 1.0);     CGContextClosePath(context);     CGContextRestoreGState(context); } @implementation UIView (WBRectView) -(void)contextRestore:(CGContextRef)context {     CGContextRestoreGState(context); } -(CGContextRef)contextSave {     CGContextRef  ctxt = UIGraphicsGetCurrentContext();     CGContextSaveGState(ctxt);     return ctxt; } -(void)drawPoint:(CGPoint)point {     [self drawPoint:point color:nil]; } -(void)drawPoint:(CGPoint)point color:(UIColor*)color {     CGRect  rect = CGRectMake(point.x, point.y, 1.0, 1.0);     [self fillRect:rect color:color]; } -(void)fillRect:(CGRect)rect {     [self fillRect:rect color:nil]; } -(void)fillRect:(CGRect)rect color:(UIColor*)color {     CGContextRef  ctxt = [self contextSave];     if (color)     {         CGContextSetFillColorWithColor(ctxt, [color CGColor]);     }         UIRectFill(rect);     [self contextRestore:ctxt]; } -(void)fillRoundRect:(CGRect)rect {     [self fillRoundRect:rect color:nil]; } -(void)fillRoundRect:(CGRect)rect color:(UIColor*)color {     CGContextRef  ctxt = [self contextSave];     roundRect(ctxt, rect, kCornerSize, kCornerSize);     if (color)     {         CGContextSetFillColorWithColor(ctxt, [color CGColor]);     }         CGContextFillPath(ctxt);     [self contextRestore:ctxt]; } -(void)strokeRect:(CGRect)rect {     [self strokeRect:rect color:nil]; } -(void)strokeRect:(CGRect)rect color:(UIColor*)color {     CGContextRef  ctxt = [self contextSave];     if (color)     {         CGContextSetStrokeColorWithColor(ctxt, [color CGColor]);     }         UIRectFrame(rect);     [self contextRestore:ctxt]; } -(void)strokeRoundRect:(CGRect)rect {     [self strokeRoundRect:rect color:nil]; } -(void)strokeRoundRect:(CGRect)rect color:(UIColor*)color {     CGContextRef  ctxt = [self contextSave];     rect = rectStrokeAdjust(rect);     roundRect(ctxt, rect, kCornerSize, kCornerSize);     if (color)     {         CGContextSetStrokeColorWithColor(ctxt, [color CGColor]);     }         CGContextStrokePath(ctxt);     [self contextRestore:ctxt]; } @end

iPhone: UITextField and the virtual keyboard, part II

April 20, 2009 8:42 pm

I’ve written about this subject before, but I didn’t do a very good job. Many weeks of intensive iPhone programming later, I am ready to deliver my definitive treatise on this subject.

The Problem

Say you’ve got a UITextField that you want the user to type something into. It’s located near the bottom of the screen. The user touches the control to begin editing. The virtual keyboard pops up, which completely covers the UITextField. It is now impossible for the user to see what she’s typing. You have to write your own custom code to move the text field out of the way before the keyboard pops up, so the user can see it.

This is against the spirit of Cocoa. AppKit on the Mac and UIKit on the iPhone normally give you decent behavior by default, and lots of hooks you can use for customization, if the defaults don’t suit your situation. In this case, they gave us a big problem by default and very little guidance towards solving it. Apple’s own example code does not do a good job with this. What we’re left with is lots of blog authors like me writing half-baked solutions to partial subsets of the problem, whereas Apple could have solved all of it, easily. Disappointing.

keyboardscroll screen-shot

keyboardscroll screen-shot

Having lived with this for awhile, I thought about how best to write something definitive, so I don’t have to keep tripping over this issue again and again. The solutions I’ve seen on programming forums and blogs involve code snippets you can drop into an existing view controller, but you have to do so every time you write a new view that contains text fields. The height of cut-and-paste code reuse.

My first idea was to add a category to UIViewController. Then every new view controller I write from now on would get textfield-handling ability “for free.” But Apple has already solved this problem for the UITableView object with special code inside UITableViewController, as of iPhone OS version 2.2. It’s not right to apply my fix to every view controller if some don’t need it. So instead I implemented a descendant of UIViewController, which can be derived from to create new view controllers.

The Solution

My keyboardscroll Xcode project shows you two ways you can solve this problem. If you’re using a UITableView, the issue is solved for you by UITableViewController, if you get all the connections right. I’ve included a table view controller that works this way, because it was harder than I thought it would be. My first attempt failed miserably. If you’re using some other view type, you can write a new view controller descended from my own WBKeyboardViewController class, which the example project shows you how to do.

My view controller works for views that contain any number of UITextFields. The content view can be a UIView or UIScrollView, either works fine. Both portrait and landscape modes are fully supported.

The only serious limitation is that my code doesn’t cope with UITextViews, which the user can also type into, and are subject to the same problem. I don’t have enough experience with text views to have a good idea about how to approach that problem yet. My first guess is that my view controller could be made to deal with them fairly easily, with a few special cases here and there.

To the greatest extent possible, I’ve avoided hard-coding pixel counts. For example, the portrait mode virtual keyboard is 216 pixels tall, and the landscape one is 162 — but those two numeric constants do not appear anywhere in the code. The proper values to use are retrieved from the operating system. Apple’s own UICatalog sample project hard-codes the height of the keyboard, so I didn’t discover that there is a better way until I had been searching for articles about this for some time.

Hard-coded pixel counts are not just a theoretical concern. “In iPhone OS 1.1.4 and earlier, the keyboard height in landscape orientation was 180 pixels.” Straight from Apple’s own documentation. Of course, that was from before the iPhone SDK existed. I think they’d be reluctant to make such a change today, since it would break so many third-party apps. Better safe than sorry, though.

There are 40 total UITextFields in my example project spread over two views, and they always, always get out of the way before the keyboard appears. I’ve tested this code thoroughly in the simulator. I’ll be using it on a real iPhone soon, so if there are issues in that scenario, I’ll find them and update this blog post. There are no bugs that I’m aware of. If you find one, I’d love to hear about it, so I can fix it.

Landscape Mode is the Devil’s Own Handiwork

Whew, this was way more complicated than I thought it would be. Apple chose to implement the landscape modes far differently than I would have. I say “modes” rather than “mode,” because there are two of them. The iPhone’s user interface can be rotated to one of four orientations: portrait, landscape, portrait upside down, and landscape upside down.

When your view rotates into landscape mode, almost all of UIKit remains stuck in portrait mode. That means you have to write lots of special cases. Here’s the first example. This code snippet gets you the bounds rect of the iPhone’s screen:

    CGRect rect = [[UIScreen mainScreen] bounds];

In portrait mode, the rect returned has a height of 480 pixels and a width of 320, which is correct. In landscape mode, the rect returned is exactly the same as the one you get in portrait mode. Erm. Okay, it’s easy enough to write a wrapper function that swaps the rect’s width and height when appropriate, which I did.

Next problem. UIView contains methods for converting rects and points from the coordinate system of one view into another, convertRect:toView: being one of them. I’ve successfully used those methods in portrait modes, but not in landscape modes. It appears to me that, while your view is in landscape mode, the main window remains in portrait mode, so translations between the two are nonsensical. I couldn’t make it work, anyway. Could be because they’re weird in the way I just described, or it could be because I don’t know what I’m doing. Either way, I had to abandon UIView’s conversion methods and roll my own.

The next problem I ran into indicates the UIKit’s designers’ intent quite strongly. UIApplication has a property called statusBarFrame. Normally I wouldn’t need to know the size of the status bar, but I was forced to roll my own coordinate conversion methods, remember. In portrait mode, the property returns a width of 320 pixels and a height of 20 pixels, which is correct. In landscape mode, it says the status bar is 20 pixels wide and 480 pixels tall! That’s obviously wrong, from the perspective of your landscape-mode view. It would be correct only from the perspective of a parent view that’s still in portrait mode. Yet another special case I had to write for the landscape modes.

It took me three days to get my view controller working right, despite the fact that it is only around 250 lines of code. Largely because I have come to trust that UIKit will Do The Right Thing in almost every case, so I could barely conceive of the idea that it would ever tell me that the status bar is 480 pixels tall with a straight face. Not at all what I was expecting, so I had to abandon a lot of early code and rethink my assumptions.

Here’s the code: keyboardscroll.zip

iPhone: UIImage rotation and mirroring

March 30, 2009 2:19 am

Update: This post has been superseded. Please go read this instead: UIImage rotation and scaling.

My access logs show that you webbernauts like my iPhone articles better than anything else on this site. Very well then, here’s another one.

I recently found myself with a need to rotate the contents of a UIImage 90 degrees to the right or left and then display it. Apparently this is easy if your image is inside a UIImageView and you’re willing to rotate the whole view, but that’s not what I have in mind. Rotating the UIImage itself turns out to be pretty danged complicated, and requires a great deal of math. I suck at math.

Fortunately for me, the code given in this guy’s blog post tackles 95 percent of the problem, and 100 percent of the math. Heh! It’s not quite what I want, however. The function given in that blog post queries the EXIF data inside the image and rotates it based on that. I want the method’s caller to be able to specify what type of rotation should be done. I tinkered with the code for awhile and got exactly what I wanted.

The original blog post’s code was written as a standalone C function. I wrote my version as a category attached to UIImage. Say you’ve got a UIImage you want to rotate 90 degrees left. It’s done like this:

    newImage = [oldImage rotate:UIImageOrientationLeft];

newImage will be a newly-created copy of oldImage, rotated 90 degrees left. Other options include UIImageOrientationRight, UIImageOrientationDown (for a new image that’s an upside-down copy of the original), and so on. There are also “mirrored” variants, which both rotate the image and mirror its contents left-to-right.

In the process of getting it to work the way I wanted, I made a bunch of changes to the code. I reformatted it so that the lines are no longer than 78 characters. (One of these days I’m going to write a blog post about why I think that’s a good thing.) The original function had two or more unnecessary copies of some data and superfluous calls to external functions, which I eliminated. The old code trimmed the size of the original image if it was bigger than a certain size, which I eliminated. The original had several copies of an identical clause for swapping the width and height of a CGRect, which I refactored into a separate helper function. There are other changes as well, but I’ll spare you the details.

Okay, one more change that I’m going to document. I am 85 percent sure that the original code has a bug. It does not work properly when the input orientation is UIImageOrientationLeftMirrored or UIImageOrientationRightMirrored. The new image gets partially chopped off along one edge, which I fixed. It could be that it was not a bug in the context where the original code was being used, but it definitely is in this new context. I’ve tested all orientations in the iPhone simulator, and they all work.

First, here’s UKImage.h, which defines the category.

// UKImage.h -- extra UIImage methods // by allen brunson  march 29 2009 #ifndef UKIMAGE_H #define UKIMAGE_H #import <UIKit/UIKit.h> @interface UIImage (UKImage) -(UIImage*)rotate:(UIImageOrientation)orient; @end #endif  // UKIMAGE_H

Now here’s UKImage.mm, which defines the rotate: method. You can rename this file to UKImage.m if you never use any C++ constructs in your code.

// UKImage.mm -- extra UIImage methods // by allen brunson  march 29 2009 // based on original code by Kevin Lohman: // http://blog.logichigh.com/2008/06/05/uiimage-fix/ #include "UKImage.h" static CGRect swapWidthAndHeight(CGRect rect) {     CGFloat  swap = rect.size.width;         rect.size.width  = rect.size.height;     rect.size.height = swap;         return rect; } @implementation UIImage (UKImage) -(UIImage*)rotate:(UIImageOrientation)orient {     CGRect             bnds = CGRectZero;     UIImage*           copy = nil;     CGContextRef       ctxt = nil;     CGImageRef         imag = self.CGImage;     CGRect             rect = CGRectZero;     CGAffineTransform  tran = CGAffineTransformIdentity;     rect.size.width  = CGImageGetWidth(imag);     rect.size.height = CGImageGetHeight(imag);         bnds = rect;         switch (orient)     {         case UIImageOrientationUp:         // would get you an exact copy of the original         assert(false);         return nil;                 case UIImageOrientationUpMirrored:         tran = CGAffineTransformMakeTranslation(rect.size.width, 0.0);         tran = CGAffineTransformScale(tran, -1.0, 1.0);         break;         case UIImageOrientationDown:         tran = CGAffineTransformMakeTranslation(rect.size.width,          rect.size.height);         tran = CGAffineTransformRotate(tran, M_PI);         break;         case UIImageOrientationDownMirrored:         tran = CGAffineTransformMakeTranslation(0.0, rect.size.height);         tran = CGAffineTransformScale(tran, 1.0, -1.0);         break;         case UIImageOrientationLeft:         bnds = swapWidthAndHeight(bnds);         tran = CGAffineTransformMakeTranslation(0.0, rect.size.width);         tran = CGAffineTransformRotate(tran, 3.0 * M_PI / 2.0);         break;         case UIImageOrientationLeftMirrored:         bnds = swapWidthAndHeight(bnds);         tran = CGAffineTransformMakeTranslation(rect.size.height,          rect.size.width);         tran = CGAffineTransformScale(tran, -1.0, 1.0);         tran = CGAffineTransformRotate(tran, 3.0 * M_PI / 2.0);         break;         case UIImageOrientationRight:         bnds = swapWidthAndHeight(bnds);         tran = CGAffineTransformMakeTranslation(rect.size.height, 0.0);         tran = CGAffineTransformRotate(tran, M_PI / 2.0);         break;         case UIImageOrientationRightMirrored:         bnds = swapWidthAndHeight(bnds);         tran = CGAffineTransformMakeScale(-1.0, 1.0);         tran = CGAffineTransformRotate(tran, M_PI / 2.0);         break;         default:         // orientation value supplied is invalid         assert(false);         return nil;     }     UIGraphicsBeginImageContext(bnds.size);     ctxt = UIGraphicsGetCurrentContext();     switch (orient)     {         case UIImageOrientationLeft:         case UIImageOrientationLeftMirrored:         case UIImageOrientationRight:         case UIImageOrientationRightMirrored:         CGContextScaleCTM(ctxt, -1.0, 1.0);         CGContextTranslateCTM(ctxt, -rect.size.height, 0.0);         break;                 default:         CGContextScaleCTM(ctxt, 1.0, -1.0);         CGContextTranslateCTM(ctxt, 0.0, -rect.size.height);         break;     }     CGContextConcatCTM(ctxt, tran);     CGContextDrawImage(UIGraphicsGetCurrentContext(), rect, imag);         copy = UIGraphicsGetImageFromCurrentImageContext();     UIGraphicsEndImageContext();     return copy; } @end