Tracking multiple NSURLConnections

A couple of years back, when I first started playing with the new Leopard (10.5) ABI’s, I was looking for a project that would allow me to play around with things like Assocaiated References (AR’s) and Blocks

I spend most of my free time maintaining both Weather Vane and Audio Switcher, which still run under 10.4 and so can’t make use of any of the new ABI. After looking at a few of the examples of the new stuff on the ‘net, I decided I would try to use them to track multiple NSURLConnections. If you need to create and dispatch multiple, simultaneous NSURLConnections, you’ll find that the  NSURLConnection ABI does not provided a means of distinguishing between the data returned from each connection. One obvious and simple solution to this problem is to subclass NSURLConnection and add some identifying field that distinguishes each connection. I did just this some years back and thought at the time, that it seemed silly to have to do that. So, I thought I’d redo that project specifically using AR’s to track each connection. If you read the docs, you know that you can use AR’s to associate arbitrary data to a given object. When the connection returns data, you inspect the data you associated with it to determine which connection it is and then do whatever you need.

This actually works pretty well, but I wanted to get some opinions from other Cocoa developers about this method of tracking connections. You can read the thread here. Many of the comments were enlightening and gave me a couple more ideas to try. Well, I’ve finally found the time to re-work the project, but this time, instead of trying to shoehorn some ABI into the project, I tried to accomplish this task in a smarter way.

So, this time I decided to wrap an NSURLConnection in an object that acts as the delegate for its connection. This proved to be much cleaner, as now the connection object essentially tracks itself. Of course, this assumes that each connection needs to handle the returned data in the same way. If different connections need to behave differently, you’ll need to try something else. The project creates multiple http request and tracks the time it takes for the headers to come back and then how long it takes for the body of the request to completely load. Not exactly sure if how I time the connections is correct, but it’s neither here nor there for this project. The important part is the connection tracking. Here’s a screen shot:

NSURLConnection timer

Each object is added to an NSArrayController and its fields are mapped to the NSTableView’s columns. Unlike the first project, though, there is no logic in code to determine which connection is which. As the values change in each connection, Cocoa Bindings handles their display, which keeps things nice and clean. You download the project here. There is a file “entries” included with the project. Its just a plist of http urls you can use to populate the table instead of manually typing in urls, if you prefer. I haven’t done a line by line comparison of the two projects, but there is at least 30% reduction in code. I’ve decided not to upload the original project. It  could use a bit of clean up, but if anyone wants to look at it, I’ll go ahead and post it.

As always, if you have ideas or questions, feel free to post.

Delaying the shutdown sequence

If the computer is in the process of shutting down, you can delay the shutdown if you need to say, put up a dialog box. If your app has an unsaved document, you need to give the user an opportunity to save, not save, or cancel the shutdown outright. There may be other reasons you need to delay the shutdown. For example, I have a simple program which displays a dialog box reminding my wife and son to turn off the wireless mouse when they shutdown. The dialog doesn’t have an OK button so it can’t be dismissed. Instead, I use a timer and a delegate function -(NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender.
When the app is told to shutdown, the delegate function is called and you have three return options:
NSTerminateNow – which allows the app to quit immediately and the shutdown to continue
NSTerminateCancel – which cancels the shutdown sequence immediately (You’ll get the user cancelled dialog box)
NSTerminateLater – which delays the shutdown sequence for a bit, giving you time to do something, such as putting up a dialog box. If the delay is too long, the shutdown will eventually be canceled. NSTerminateLater also causes your app to be placed a new runloop mode, NSModalPanelRunLoopMode. Now, if you want to use a timer to dismiss the dialog you’ve put up, such as in my app, you have to take care to place your timer in the NSModalPanelRunLoopMode, otherwise, your timer will never fire. There are 4 class methods for creating an NSTimer:

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds
invocation:(NSInvocation *)invocation repeats:(BOOL)repeats

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds
target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds
invocation:(NSInvocation *)invocation repeats:(BOOL)repeats

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds
target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats

The first two, automatically place the NSTimer in the default runloop, so if you use either of these in this situation, the timer will never fire. Use one of the last two and then you’ll need to manually place the timer in the correct runloop, ala,

[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSModalPanelRunLoopMode];

Of course, when you initialize your timer, you need to give it a method to invoke. Within the body of that method, you can just this send this message to NSApp passing YES as the lone parameter:

- (void)replyToApplicationShouldTerminate:(BOOL)shouldTerminate

I have a sample app here. (The crash issue is now fixed)

One other thing to note is the new “Sudden Termination” feature of Snow Leopard (10.6). To speed up shutdown/restart, the OS will immediately terminate an application if it allows for sudden termination. You can read the documentation here in the:

NSProcessInfo docs.

The upshot of this is that if your app should not abruptly quit (in Snow Leopard), you need to disable sudden termination. You can either do this in code ([[NSProcessInfo processInfo] disableSuddenTermination]) or in the app’s plist (NSSupportsSuddenTermination NO). Whatever route you choose, you can re-enable sudden termination in code via [[NSProcessInfo processInfo] enableSuddenTermination].

That’s it.

Capitalize first character of an NSString

While localizing Weather Vane, I found that the non-English forecasts returned from AccuWeather are always returned with the forecast in all lower case. The English forecast returns a string with the first character in the string capitalized; like a sentence. Makes sense to me, so I thought I’d just find the method in NSString that would do that for me. Well, there isn’t one, so what did I do? Category time! Here’s what I did:

-(NSString*) stringWithSentenceCapitalization

NSString *firstCharacterInString = [[self substringToIndex:1] capitalizedString];
NSString *sentenceString = [self stringByReplacingCharactersInRange:NSMakeRange(0,1) withString: firstCharacterInString];

return sentenceString;

The only gotcha here, if there is one, is that

(NSString *)stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement

is Leopard (10.5) and above only, so if you need to support 10.4 (as I do), you need to do something else.

Here’s what I did in Weather Vane:


// Get the first character in the string and capitalize it.
NSString *firstCapChar = [[str substringToIndex:1] capitalizedString];

NSMutableString * temp = [str mutableCopy];

// Replace the first character with the capitalized version.
[temp replaceCharactersInRange:NSMakeRange(0, 1) withString:firstCapChar];

return [temp autorelease];

As always, if you find a better way, please let me know.

List of fonts installed on the iPhone/iPad

I finally got around to updating this for the iPad. The project is setup for iOS 6. One other point I should add:
After converting this to support iPad, I noticed an annoying problem where the content of a given cell would “disappear” when the cell reappeared in the view after scrolling. Undrawn cells below or above the view would appear empty when first scrolled onto the screen. This only happened when the device, iPhone or iPad, was lying flat on a table. I tracked this down to a couple of issues with my cellForRowAtIndexPath method.
First, never do any more inside the if(cell==nil) clause than is needed in every cell. Remember if the cell is reused, anything inside that clause won’t get executed when another cell is requested. In this example. All I do is initialize the cell, set the minimum font size and constraint width of the text, every cell needs those. The text, which varies with each cell, is after the ‘if’ clause. Also, I had to replace initWithFrame with initWithStyle:reuseIdentifier, not sure why I was doing it the other way. The real problem I found is that, for example, when you place an iOS device flat on a table, [[UIDevice currentDevice] orientation] will always return UIDeviceOrientationFaceUp. My code was adding the text without considering this situation, so neither of my if/else clauses was executing, therefore no text. So I just check for landscape orientation and draw the text accordingly, or portrait when face up. That’s it.

Just a quick post to show how you can get a list of the fonts installed on the iPhone. There are lists available on the internet, but I was bored one day and decided to write an iPhone app that displays them all in a grouped table view subdivided by font family. Its based on some sample code I found here. The only problem with that code is that since it outputs the results to the console, you don’t know how the font actually looks. This little project displays each font string using the font itself. There’s also a simple example of how to create and initialize a table header view from a xib. Here’s the project. Sample output is here:
FontViewer output

I hope you find this useful.

Mutually exclusive NSTableView selections

While developing Weather Vane, I ran into a problem trying to bind a selection from one of two different tables to a location ivar, which can only reflect the value of one selection at a time. In Weather Vane’s preferences, when a user does a search for a city, multiple results may be returned, some international and some US. International and US results are placed in separate tables. If the user selects a US city, the ivar is updated as expected. If the user then selects an international city, the ivar is again updated, but if the user then reselects the original US city, the ivar is not updated. The reason had to do with how and when the NSTableViewSelectionDidChangeNotification is sent.

When the initial selection was made in the US table, the notification is sent, the same occurs when a selection is made in the international table. But when the same selection is made again in the US table, the original selection is still valid even though the US table lost focus when the international selection was made, so reselecting it does not trigger an NSTableViewSelectionDidChangeNotification.

When the NSTableViewSelectionDidChangeNotification is sent, an NSTableView delegate method is invoked (if you’ve chosen to be notified of selection changes, or set some class in your project as the NSTableView’s delegate):

– (void)tableViewSelectionDidChange:(NSNotification *)aNotification

My initial attempt to resolve the selection problem tried to handle the problem in this method by deselecting everything in the ‘other’ table (the one losing focus), but what I found is that this led to additional notifications being sent. Every selection triggers a notification AND every deselection triggers a notification as well. One could easily end up with looping notifications this way, which is a problem.

I have a small project which illustrates the problem. You can download it here. (Please note: Although I called the project mutex_tables, one should not confuse this with locks of any sort). The name was determined from the mutually exclusive nature of the tables.

When the tables are initially populated, things look like this:
Initially populated tables

Once a selection is made, an NSTextField below the tables has its stringValue set (like my location ivar).
Initial selection made, NSTextField updated.

After making a selection in the second table, the NSTextField is also updated:
Second selection made, NSTextField updated.

Notice, the selection in the first table, although grayed out since the table has lost focus, is still highlighted.

Now, if we select the same item in the first table, nothing happens. Since technically, there is no change in the selection, the notification is not fired and the text field is not updated.
Original selection made, NSTextField NOT updated..

The solution I found is to use another delegate method,

-(BOOL)tableView:(NSTableView*)aTableView shouldSelectRow:(NSInteger)rowIndex

to handle the deselection in the ‘other’ (unfocused) table.

When called, a selection is about to made in one of the tables. What I do then is deselect everything in the ‘other’ table. Now, in tableViewSelectionDidChange, I can just “find” the new selection and update the textfield accordingly. tableViewSelectionDidChange will be called once on the initial selection, and twice thereafter, but never more than twice. Two notifications seem to be unavoidable.

Here’s how things look now after I implemented the new delegate method:

Initial unselected view:
Initially populated tables

After first selection is made:
Initial selection made, NSTextField updated.

After second selection in the other table is made:
Second selection made, NSTextField updated.

But now with our newly implemented delegate method in place, reselecting the original item in the first table, things work properly:
Reselect initial item in the first table, NSTextField updated.

Nothing in the unfocused table is highlighted and as selections are made between the tables, only the current selection in the current table will be highlighted.

Here is my implementation of tableView:shouldSelectRow:

-(BOOL)tableView:(NSTableView*)aTableView shouldSelectRow:(NSInteger)rowIndex{

// Deselecting generates an NSTableViewSelectionDidChangeNotification
// notification.
if (aTableView == self.secondTableView) {
[self.firstTableView deselectAll:self];
else {
[self.secondTableView deselectAll:self];
return YES;

And my tableViewSelectionDidChange
// This will be called once on the initial selection
// twice thereafter.
– (void)tableViewSelectionDidChange:(NSNotification *)aNotification{

NSDictionary * item = nil;
NSUInteger index;

// Make sure we have the right table and ignore no-selection
if([aNotification object] == self.firstTableView && [self.firstController selectionIndex] != NSNotFound){
index = [self.firstController selectionIndex];
item = [self.firstTableArray objectAtIndex:index];
else if([aNotification object] == self.secondTableView && [self.secondController selectionIndex] != NSNotFound){
index = [self.secondController selectionIndex];
item = [self.secondTableArray objectAtIndex:index];

// When two notifications are sent, item will be nil on first notification
if (item) {
[self.selectionField setStringValue:[item objectForKey:@”test”]];

You can download the updated project here.

By the way, don’t forget to check the “Avoid Empty Selection” box for the associated NSArrayController.

I hope people find this useful. If someone has a better way, please feel free to comment.