More of a programming nerd than is strictly healthy. See also {nevyn.nu, thirdcog.eu, twitter}

Projects

Overooped

Low Verbosity KVO

DRY Cocoa: SPLowVerbosity

I love Objective-C. It’s a very explicit language: there is no magic in the language. If you want such magic as distributed objects, model classes generated at runtime, generic change notification, or heck, even referenced counted memory management, you can implement it yourself in a library. It’s also by convention a very verbose language. If the method name doesn’t say exactly what the method does, the author is doing it wrong.

However, there are some things we type over and over again every day, whose verbosity does not make the code more readable but only serves to pad the code file with useless characters. These are in particular array and dictionary literals, and formatted strings.

ObjC wizard Jens Alfke wrote MYUtilities quite a while ago, and in particular CollectionUtils. This header defines a few very handy macros such as $array(...), $dict(...) and $sprintf(...). $array is simply a shorthand for [NSArray arrayWithObjects:..., nil] (note the extra nil, freeing you from typing that yourself every time, and also avoiding a possible crash). $dict is NSDictionary’s constructor, with the arguments in the right order (key, value, key, value, …). $sprintf is [NSString stringWithFormat:]. It may seem trivial, but this simple header has saved me tons and tons of typing, and surely from some silly bugs as well.

For more C++ friendliness, and to not have to depend on the rest of MYUtilities, I wrote my own, called SPLowVerbosity, with mostly the same things. The details are not interesting, so I won’t list the code; click through if you are curious.

This is a hack, and while it is very convenient, it is not pretty. Objective-C needs in-language literals for arrays, sets, dictionaries and number objects.

I do believe that such literals are now inevitable, though. With ARC, what I wrote in the first paragraph is no longer entirely true. Dealloc now magically calls super. Memory management is implicit and part of the language, not explicit and manual. The sanctity of Objective-C’s simplicity has been violated, parts of Cocoa has been moved into the language. Moving more parts of Cocoa into the language (e g exposing APIs saying ‘this is the class that should be instantiated when I use a dictionary literal’) no longer has a high religious price, and I bet we’ll see it at next year’s WWDC.

Object-Oriented KVO: SPKVONotificationCenter

During the past few years, my nose has started to really pick up on a code smell I didn’t feel before: unencapsulated concepts. What I mean by that is an API concept or contract that is only visible in comments and documentation, thus only implicit by knowledge of that documentation when you read code using the API, instead of exposing the concept as a construct the language can help you manage.

Examples:

Instead of the above concepts being implicit and only visible in documentation, several of them can be represented as objects and closures, thus making it impossible to do wrong.

The realization is not new, of course. It’s quite common to use RAII patterns in C++ to encapsulate concepts in code, giving them an explicit start point and a managed (and deterministic) end point.

But this is Objective-C, not C++, so we don’t have RAII. We do have objects, however, and if we use them to actually represent our objects, we can clean up so much code.

SPKVOObservation is an object that represents a KVO subscription. When this object is created, you know you have your subscription. When this object disappears, you know the subscription is gone. By managing instances of this class like I would any other instance variable, I know I’m following KVO’s subscribe/unsubscribe contract. (With ARC, I don’t even have to manage the ivar).

SPKVONotificationCenter also has dispatch to a given selector instead of the catch-all -[NSObject observeValueForKeyPath:ofObject:change:context:].

(As for solutions for the rest of the examples: a closure can be used for the mutex case if in the current scope, otherwise you might want RAII (which is possible with GNU extensions even in C). For the table view, I’d prefer bindings, but doing to-many KVO and bindings can be really hard, so I doubt we’ll be seeing it on iOS in the near future.)

DRY KVO: SPDepends

I love KVO. Basically every library I’ve ever used has their own implementation of notifications on attribute changes. Such an implementation is of course not difficult, but because there is no generic system for it in other languages/platforms, you can’t build a framework for working with change notifications generically. Recognizing that this is a generic concept, and then as good as building it into the language is genius, and has given us wonders such as bindings.

Outside of their use in bindings where you have tool help, KVO’s API is pretty bad, and working with it is almost painfully verbose (made worse by the single callback point, spreading your code out all over the file). What I really wanted to do was to unify the two above sections for a very simple, non-verbose and object oriented approach to KVO. The result is SPDepends. Magic is taken to the next level; we are approaching dark arts. Whether what I’m about to present is actually a good idea or not, I leave as an exercise for the reader. First, the header:

tl;dr: SPDepends lets you give it a list of {object, key path(s)} pairs that one of your properties depend on. When the value of any of the given key paths changes, a given closure is called, letting you recalculate the dependent property (or whatever you want to do). It’s about as far as you can go with KVO without actually building bindings.

There is one additional piece of magic related to memory management (this was before ARC). By providing an owner and associationName, the dependency is assigned as an associatedObject, so that it will automatically be cleaned up when the owner object dies. Defining a dependency again with the same name will also throw away the old dependency. If this is not desired, you can just not provide the association name, and instead manage the returned SPKVOObservation object on your own.

Example:

Output:

Note how short the $depends macro makes all your KVO work. The macro also defines a block-safe self variable selff that won’t create a reference cycle.

The equivalent classical KVO code would be many lines longer. However, this macro takes several steps away from how Cocoa code is normally written. Is the syntax too obscure? Is the code still readable for normal human beings?

UIKit: Hide the keyboard without a reference to the currently focused text field

Googling for answers to UIKit or iOS/iPhone programming problems today resembles googling for answers to JavaScript problems. There is so much horribly, horribly broken code out there, being promoted as the way to do things. Ranting aside, today’s problem is writing your own view controller container, and noticing that focused UI elements don’t dismiss their keyboard in response to viewWillDisappear: or similar. If this was MacOS, or AppStore approval didn’t exist, you’d just do [self.view.window.firstResponder resignFirstResponder]. You can’t do that though, firstResponder is private on window, don’t ask me why. cdyson37 on StackOverflow however, found the public API -[UIView(UITextField) endEditing:] hidden in a category in UITextField.h, that supposedly looks recursively through the receiver’s children for the first responder, and if found, resigns it. Perfect! A copy-pasteable code snippet for lazy googlers:

[self.view endEditing:YES]

Media keys hook in Mac OS X

There is no nice (or is it even official?) way of detecting and handling the media keys on the user’s keyboard. One can intercept events with type NSSystemDefined and subtype 8 in -[NSApplication sendEvents:], but this has major problem: any other applications that listen to the media keys will receive these events too. This means for example that if only Spotify is running and you want to pause your music, iTunes will start when you press play/pause. If you have VLC running in the background, it will also start playing.

Apple has solved this problem internally by having their media key using applications cooperate and resign media key controls to the application that was in the foreground most recently. However, there is no way for third party applications to join this cooperation.

I have implemented a workaround that does this using a CGEventTap in the Cocoa class SPMediaKeyTap. The advantage of using an event tap instead of just intercepting the events in -[NSApplication sendEvent:] is that you have the power to throw the event away. This way, we can decide to “own” the media keys and be the only app that listens to them.

This class is smart enough to resign the media key event tap whenever another application that we know will want to use the media keys becomes active, and keeps track of which media key using app was recently started.

If everyone uses this class, and everyone add each other’s bundle ID to that list of whitelisted bundle ID’s, we’ll get nice behavior from all apps. An even better solution would be if Apple provided a way of acquiring the media keys.

Filtering a UITableView, and keyboard wonkiness

Hey, another bug that took half a day to fix. That always deserves a blog entry.

So I have a UITableView, and on it I have a tableHeaderView containing a UISearchBar. The UISearchBar filters the contents of the UITableView, and thus at every key press I have to reloadData (or more specifically, I -[UITableView reloadSections:withRowAnimation:]). For some reason, this calls setUserInteractionEnabled:NO on the UITableView, which in turn makes the UISearchBar’s UIFieldEditor resignFirstResponder, which makes the keyboard collapse. After the reload, user interaction is restored, UISearchBar gets focus, and the keyboard comes up.

This is rather embarrassing: I even subclassed UITableView, disabling setUserInteractionEnabled, before I realized that right there, before my eyes, is a UISearchBar delegate method called -[UISearchBarDelegate searchBarShouldEndEditing:]. Just add a bool ivar to the view controller saying whether the search bar may be resign key, set it to false before refreshing, refresh, and set it to true, and in the above delegate, return the ivar bool. Done, no more disappearing and reappearing keyboards.

Oh, and the code:


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
	_searchBarMayResign = NO;
	[self.tableView reloadData]; // or equivalent
	_searchBarMayResign = YES;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar;
{
	return _searchBarMayResign;
}

 The write-compile-test cycle is very very tedious when doing iPhone development on the device, because the “compile” step needs to include “install on device”, which can be very, very slow. It can take up to a minute, depending on how many apps you have installed and the current cycle of the moon. Imagine, then, doing tiny interface changes and you want to see how that tiny fix changes the UI (which sometimes you really need to do on the device to get a feel for it) — ten tries changing an animation delay could mean ten minutes of just waiting for installation. If you’re jailbroken, there is an easier faster way.

In Cydia, install ldid, rsync and ssh
Follow this guide to install an ssh key pair on your iPhone, so that the script can install the app without asking for password.
Add an additional build target to your app, and call it “Upload” or something.
Make that build target depend on your real app (as in the picture above)
Add a “run shell script” build phase, and give it this script:
export DEVICE_NAME=Mishimazu.local
rsync -avz "${CONFIGURATION_BUILD_DIR}/${PROJECT}.app" root@${DEVICE_NAME}:/Applications/
ssh root@${DEVICE_NAME} ldid -s "/Applications/${PROJECT}.app/${PROJECT}"
Replace “Mishimazu” with the name of your iPhone.
Change your active target to “Upload”, and build as usual.
A few notes though.
This script does not launch the app, you’ll have to do that yourself.
You don’t get the console routed to Xcode. Open up the Console in the Organizer for a workaround (not as good though)
Xcode debugger won’t work
File locations might have changed! You no longer have your private uuid bundle with your documents, but rather need to place documents and related things in /var/mobile. It’s possible NSSearchPathForDirectoriesInDomains will figure the right paths out for you, I haven’t tested; just make sure you’re aware of this
You are no longer sandboxed. This might change assumptions you do in code


In short, only use this deployment method for simple things, and install as usual when you need to really make sure things still work as they should, before a beta or appstore deploy. Of course, if you’re targeting the Cydia store or similar, that doesn’t apply.

The write-compile-test cycle is very very tedious when doing iPhone development on the device, because the “compile” step needs to include “install on device”, which can be very, very slow. It can take up to a minute, depending on how many apps you have installed and the current cycle of the moon. Imagine, then, doing tiny interface changes and you want to see how that tiny fix changes the UI (which sometimes you really need to do on the device to get a feel for it) — ten tries changing an animation delay could mean ten minutes of just waiting for installation. If you’re jailbroken, there is an easier faster way.

  1. In Cydia, install ldid, rsync and ssh
  2. Follow this guide to install an ssh key pair on your iPhone, so that the script can install the app without asking for password.
  3. Add an additional build target to your app, and call it “Upload” or something.
  4. Make that build target depend on your real app (as in the picture above)
  5. Add a “run shell script” build phase, and give it this script:
    export DEVICE_NAME=Mishimazu.local
    rsync -avz "${CONFIGURATION_BUILD_DIR}/${PROJECT}.app" root@${DEVICE_NAME}:/Applications/
    ssh root@${DEVICE_NAME} ldid -s "/Applications/${PROJECT}.app/${PROJECT}"
  6. Replace “Mishimazu” with the name of your iPhone.
  7. Change your active target to “Upload”, and build as usual.

A few notes though.

  • This script does not launch the app, you’ll have to do that yourself.
  • You don’t get the console routed to Xcode. Open up the Console in the Organizer for a workaround (not as good though)
  • Xcode debugger won’t work
  • File locations might have changed! You no longer have your private uuid bundle with your documents, but rather need to place documents and related things in /var/mobile. It’s possible NSSearchPathForDirectoriesInDomains will figure the right paths out for you, I haven’t tested; just make sure you’re aware of this
  • You are no longer sandboxed. This might change assumptions you do in code
  • In short, only use this deployment method for simple things, and install as usual when you need to really make sure things still work as they should, before a beta or appstore deploy. Of course, if you’re targeting the Cydia store or similar, that doesn’t apply.

xib + subversion + automerge = pain

Don’t let Subversion automerge your xib files. This error isn’t even on the freakin’ google:

ibtool: some object IDs were duplicated

You can work around this by 1) telling subversion the file can’t be merged by setting its mime type to application/octet-stream 2) requiring the file to be svn locked before you edit it for an exclusive lock. You can tell your subversion client to automatically give xib files these properties by adding a few lines to your ~/.subversion/config file.


## Under [miscellany]
enable-auto-props = yes

## under [auto-props]
*.nib = svn:mime-type=application/octet-stream;svn:needs-lock=*
*.xib = svn:mime-type=application/octet-stream;svn:needs-lock=*

Of course, your merged xib is still beyond saving, so just fetch the previous version and redo all your changes! (also, more on subversion locking and exclusive checkouts)

NSFileHandle Considered Harmful [Updated]

Update 20090627: This bug has been fixed in 10.6. I’d still only recommend using it for very simple cases, but at least it works now!

NSFileHandle has a bug where the calling thread will lock up indefinitely if a data of size >4096 is requested. Reduced case:


#import 

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSFileHandle *fh = [[NSFileHandle alloc] initWithFileDescriptor:fileno(fopen("/dev/random", "r"))];
    
    NSLog(@"Reading 4096 bytes... This will succeed.");
    [fh readDataOfLength:4096];
    NSLog(@"Reading 4097 bytes... This will lock for infinity");
    [fh readDataOfLength:4097];
    NSLog(@"This will never be printed.");
    
    [fh closeFile];
    [fh release];

    [pool drain];
    return 0;
}

(Warning: running this program might lock up your computer; killing the rogue process is difficult as NSFileHandle will read an infinite amount of data from /dev/random, swapping out your OS.)

This is extra dangerous if your read length is dynamic, such as in a protocol where the first incoming bytes defines how long the upcoming chunk to read is.

Solution: Use the C API for working with file descriptors instead, such as read() and write(). A file descriptor can be extracted with [NSFileHandle fileDescriptor] if you receive one from another API.

(This bug has been reported.)

[Cocoa] Less code when working with delegates

The usual pattern is to do this in your class that has a delegate:

-(void)frobnicate;
{
  ...
  BOOL extraJuicy = NO;
  if(delegate && [delegate respondsToSelector:@selector(frobnicatorShouldAddJuice:)])
    extraJuicy = [delegate frobnicatorShouldAddJuice:self];
  if(extraJuicy)
    ...
  ...
}

for every delegation method, which gets old, fast.

With DelegationHelper, you can do this:


// Setup
@interface FrobnicatorDelegationHelper : DelegationHelper  {} @end

@interface Frobnicator... { FrobnicatorDelegationHelper *delegate; ... } ...@end

@implementation
-(void)setDelegate:(id)delegate_
{
  delegate = [[DelegationHelper alloc] init];
  delegate.delegate = delegate_;
  
  [delegate setDefaultDelegationObject:BOOLobj(YES) forSelector:(frobnicatorShouldAddJuice:)];
}

// And then just...
-(void)frobnicate;
{
  ...
  if([delegate frobnicateShouldAddJuice:self])
    ...
  ...
}

Okay, the setup requires three extra lines and one line per selector (for defaults), but we’ve cut down the actual delegate calls from four lines to one! So if you have more than a single delegate method for your class, the DelegationHelper will help you.

For more samples, see main.m in my repository.

My brother needed some math homework help figuring out quadratic equations. I really want to teach him programming and I’ve shown him some very basic C before, so together we threw together a quick app solve quadratic formulas with the pq-formula :) [note: he chose project name :P]

(If you are a beta tester for any of my apps, you can even download and install the app and try it yourself!)

My brother needed some math homework help figuring out quadratic equations. I really want to teach him programming and I’ve shown him some very basic C before, so together we threw together a quick app solve quadratic formulas with the pq-formula :) [note: he chose project name :P]

(If you are a beta tester for any of my apps, you can even download and install the app and try it yourself!)

Updated my Mac Frameworks page with GLEW 1.5.0.