Archive for the 'cocoa' category
iPhone: nibless
February 28, 2010 5:07 pmI 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.
Categories: cocoa, iphone, objective-c, programming
Comments Off
UIProgressHUD replacement
February 27, 2010 11:22 pmDear 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.
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.
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.
Categories: cocoa, iphone, objective-c, programming
Comments Off
iPhone and iPad SDK coexistence
February 14, 2010 7:14 amApple has released a new SDK specifically for iPad. It’s not yet ready for prime-time, so if you want to continue to develop for iPhone, you’ll need to use both the old and new SDKs for awhile. Curious about the logistics of this endeavor, I googled up this article. I dutifully followed the instructions and installed the beta 1 release in a separate dev directory. Yeah, I’m calling shenanigans. It did not work. I think it’s a bit irresponsible to post something like that without having tried it.
You can’t completely separate the two SDKs. According to the release notes, the one that is installed last is the one whose compilers will be used for both. I had other problems as well. Both the old and new device simulators were crashy. So I completely wiped both sets of dev tools and reinstalled the iPhone SDK.
Recently, Apple released beta 2 of the iPad SDK. They may have fixed the problems I experienced before, but I’m not taking any more chances. This time, I got myself an external Firewire hard drive. USB 2.0 would also work, but I prefer Firewire for a possibly frivolous reason: I have so many USB devices that it’s difficult to find a place to plug in a new one, but I have two Firewire ports on the back of my Cinema Display that are otherwise unused.
This next part is important. You’re going to need to boot off this drive, so its partition map scheme must be set to “GUID Partition Table.” If it isn’t, you should reinitialize it so that it is. On the Mac, you use the Disk Utility program for this. It doesn’t create GUID partition tables by default, so you have to press the button that says “Options…” and change it.
Next, use a program like Carbon Copy Cloner to make a copy of your primary hard drive onto the external drive. Finally, in System Preferences, pick “Startup Disk,” select your external hard drive, and reboot. Now install the new iPad SDK. It will be copied onto your external disk, leaving your primary disk alone. This way, the two SDKs won’t butt heads with each other.
It’s a shame that Apple is making us solve a software problem with hardware, but this is the sort of inconvenience you have to put up with if you want to live on the bleeding edge. I can’t even remember the last time I had to use the Startup Disk pref pane before this. It’s been years, surely. This reminds me of when I used to work at Be, and we had a new version of BeOS to install every couple of weeks.
Categories: cocoa, ipad, iphone, programming
Comments Off
iPhone: UIImage rotation and scaling
January 31, 2010 8:03 pmHello 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
Categories: cocoa, iphone, objective-c, programming
Comments Off
iPhone: keyboard trouble
August 28, 2009 3:07 am
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.
Categories: cocoa, iphone, objective-c, programming
Comments Off
NSLog() sucks
July 18, 2009 8:15 amIn 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; }
Categories: cocoa, iphone, mac, objective-c, programming
Comments Off
Drawing NSStrings in unusual rotations
June 1, 2009 8:10 pmIf 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.
Categories: cocoa, iphone, objective-c, programming
Comments Off
Beta testers wanted
May 14, 2009 1:42 amMy blog traffic has grown exponentially. I am as baffled as anyone that one of my entries is the top google hit for “cocoa task_info”, as an example. Seems like a lot of people found me that way, and at least some of you are now RSS subscribers.
So, perhaps a few of you would like to help me beta-test my almost-finished game? I set up a new subsite for it, here: Hearts Solo. I am especially interested in hearing from people who have iPhone 3G or iPod Touch devices, because I haven’t tested my game on either of those. I got a lot of really good beta testers for the two big releases of my USENET newsreader, so I’m hoping I can do as well this time.
One of my goals for this project is to scare up some new iPhone work. I’m not currently working on anything that’s making me any money. If you need some iPhone or Mac programming done, I’d love to hear from you! allen.brunson@gmail.com
Categories: cocoa, iphone, programming
Comments Off
cocoa: app memory usage
May 3, 2009 6:30 pmMy 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.
Categories: cocoa, iphone, mac, objective-c, programming
Comments Off
iphone: drawing rectangles
April 28, 2009 9:33 amMac/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
Categories: cocoa, iphone, objective-c, programming
Comments Off



