Snippet: code to convert RGB to HSV and back again

I sketched this code together needing a quick way to convert from RGB to HSV and back again, then realized I didn’t need it. So I’m putting it here in the theory that this may be useful someday…

/*	RGBToHSV
 *
 *		Conver to HSV
 */

static void RGBToHSV(float r, float g, float b, float *h, float *s, float *v)
{
	float max = r;
	if (max < g) max = g;
	if (max  g) min = g;
	if (min > b) min = b;
	
	/*
	 *	Calculate h
	 */
	
	*h = 0;
	if (max == min) h = 0;
	else if (max == r) {
		*h = 60 * (g - b)/(max - min);
		if (*h = 360) *h -= 360;
	} else if (max == g) {
		*h = 60 * (b - r) / (max - min) + 120;
	} else if (max == b) {
		*h = 60 * (r - g) / (max - min) + 240;
	}

	if (max == 0) *s = 0;
	else *s = 1 - (min / max);

	*v = max;
}

/*	HSVToRGB
 *
 *		Convert to RGB
 */

static void HSVToRGB(float h, float s, float v, float *r, float *g, float *b)
{
	if (h  359) h = 359;
	if (s  1) s = 100;
	if (v  1) v = 100;

	float tmp = h/60.0;
	int hi = floor(tmp);
	float f = tmp - hi;
	float p = v * (1 - s);
	float q = v * (1 - f * s);
	float t = v * (1 - (1 - f) * s);
	
	switch (hi) {
		case 0:
			*r = v;
			*g = t;
			*b = p;
			break;
		case 1:
			*r = q;
			*g = v;
			*b = p;
			break;
		case 2:
			*r = p;
			*g = v;
			*b = t;
			break;
		case 3:
			*r = p;
			*g = q;
			*b = v;
			break;
		case 4:
			*r = t;
			*g = p;
			*b = v;
			break;
		case 5:
			*r = v;
			*g = p;
			*b = q;
			break;
	}
}

Objective C declaration shortcuts

With a recent update (okay, not quite so recent update) to Objective C, the following lexical shortcuts appear to have been added:

Create a dictionary using @{…}

The @{ … } shortcut has been added to create a new NSDictionary with a list of keys and values. The format appears to be:

@{ key : value , ... }

So, to create a new dictionary with three keys:

NSDictionary *d = @{ @"a": @"First",
                     @"b": @"Second",
                     @"c": @"Third" };

This creates a dictionary with three keys: @”a”, @”b” and @”c”, with the values @”First”, @”Second” and @”Third”, respectively.

Create an array using @[ … ]

The @[ … ] shortcut creates a new NSArray with a list of values. The format appears to be:

@[ value, value, ... }

So, to create a new array with three items:

NSArray *a = @[ @"a", @"b", @"c" ];

This creates an array with three items, @”a”, @”b” and @”c”.

Create an NSNumber wrapper around a numeric constant using @(…)

The @(…) appears to take a scalar and wrap it in an NSNumber object. Thus:

NSNumber *n = @( 5 );

creates a new NSNumber with the value 5.


You can combine each of these together in any way you wish. For example:

NSDictionary *d = @{ @(1): @[ @"A" ],
                     @(2): @[ @"Another", @"Thing" ],
                     @(3): @[ @"Tom", @"Dick", @"Harry" ] };

Far more convenient than the old way.


I’ve seen the first two documented elsewhere, but I don’t think I’ve seen the third one (boxing an NSNumber) mentioned anywhere, and I don’t quite remember where I saw it. Probably in the compiler release notes.

Also note that these can be used in-line with code and not just with constant objects. So, for example, you can use the NSNumber boxing mechanism to box an integer return value from a function:

NSNumber *count = @( [array count] );

This has been a public service announcement.

My love/hate relationship with Design Patterns.

I have a love/hate relationship with Design Patterns, which is actually captured in the first two sentences of the Wikipedia article I just linked to.

I love them because they provide a general reusable solution–a rule of thumb, so to speak–on how to solve some fairly common problems.

For example, if you are developing a user interface application, then the Model-View-Controller pattern or the Model-View-Presenter pattern is definitely a lifesaver in helping you design a well-organized application.

(The difference between the two have to do with the ability of view components having direct access to the model data: MVC allows the connection as a rule of thumb, while MVP denies it. For most applications–such as simple iOS applications which access remote data from a database and present the results on a screen–strictly separating views from the model object makes a tremendous amount of sense. However, there are certain types of applications where the user interaction of the view with the data is so involved, you need to allow the view insight into the model data directly. Usually this is reserved for complex editing applications, like a text editor or a CAD system, where the logic for handling key or mouse events makes more sense to contain in a text editor view or a CAD drawing view than allow the raw events to percolate to an already over-loaded controller module.)

And having a good working knowledge of various design patterns helps you have a standard bag of tricks to apply to problems you may see in the field: singletons, proxies and modules are excellent ways to handle organization of conceptual functions. Flyweights are helpful when creating a complex page of preferences in a dialog. Object pools help with reducing the overhead of allocation. And so forth.


I hate them, though.

And I hate them for the very simple reason that to an inexperienced developer equipped with a hammer, the entire world becomes full of nails.

Design patterns are, as defined in Wikipedia, “general reusable solutions to commonly occurring problems.”

And there are three problems with that.

First, it requires some degree of understanding of the solution and how to apply it. If you don’t understand the ‘chain of responsibility’ pattern, for example, then you can really shoot yourself in the foot if you implement it poorly–as I’ve seen done on a number of occasions, with events in a custom event chain that just “disappeared”.

Second, it requires some degree of understanding what the problem was the solution is attempting to solve. One developer I had a conversation with a long time ago insisted on using a decorator pattern to allow a view to both have presentation and editing functionality, when either a flyweight or simple inheritance could have solved the problem far more gracefully.

And third, many developers labor under the presumption that these are the only solutions–that there are no other solutions out there. The whole world becomes full of nothing but nails, and by God if my hammer doesn’t work the problem is not solvable by us “mere mortals.”


To me, design patterns are just solutions to common problems. There are other potential solutions to other problems not quite as common: for example, I once wrote a networking stack for a small microprocessor by creating a state machine: a large switch statement where each ‘case’ ended by changing the variable controlling the state machine to the next ‘case’ that was to be executed.

Emulating multi-threading was achieved by having each network connection hold its own state–and on exit of each case, a pointer pointed to the next active network object and picked up with whatever state that network object was in.

(I’ve successfully used state machines to solve a number of esoteric problems, including building my own LISP interpreter, and my own virtual machine interpreter. And state machines are built by YACC for building a parser; they’re far more flexible than recursive-descent parsers.)

And there are many solutions I’ve come across which solve common problems related to multi-threading that I’ve yet to see written down as an “approved” Design Pattern, such as the solution I provide here, to solve the problem of anonymous inner blocks which may be deallocated by a user action prior to the completion of an asynchronous task.


Principally I hate design patterns for the same reason I hate orthodoxy: it’s just an excuse to stop thinking now that all of the approved answers have been derived for us.

44 Is the Magic Number, and the Magic Numbers is 44.

iOS Human Interface Guidelines: Layout

Make it easy for people to interact with content and controls by giving each interactive element ample spacing. Give tappable controls a hit target of about 44 x 44 points.

So if you’re designing something for iOS, please for God’s sake, stop designing 18-pixel tall buttons.

I’m looking at you, Apple’s ‘delete application’ button in the home page…

iOS Notifications

Working through iOS notifications, and found an excellent article here:

Apple Push Notification Services in iOS 6 Tutorial: Part 1/2

Apple Push Notification Services in iOS 6 Tutorial: Part 2/2

Note that the steps for setting up a certificate have not changed, and worked like a charm for me.


Followup: when attempting to load the certificates into Amazon’s SNS service through the console, I ran into the dreaded “There was a transient failure registering the app with Amazon SNS.”

*sigh*

The trick is hinted at here: Amazon SNS with Apple APN

The trick is that you load the aps_development.cer file (or the APN certificate for release; I haven’t done that so not clear what it’s called) into Keychain by double-clicking on the file.

Then you select both the private key that was used to generate the certificate, and the APN certificate you just added to Keychain, and export both as a .p12 file.

Convert into a .pem file via

openssl pkcs12 -in InCert.p12 -out OutCert.pem -nodes -clcerts

This OutCert.pem can then be used as the single .pem file that Amazon asks for in the SNS console.


I hate when I run into weirdness like this.

Where am I?

We’re moving across country, and my folks bought me a Spot satellite tracking device. (Actually it’s for flying–I’m a newly minted IFR-rated pilot–so this allows folks to know where I am in an emergency. But as we drive across country it serves the secondary purpose of checking in with our current location.)

So after January 14th check in here to find out where we are as we drive across the country.

iOS Development Sins

Some random sins I’ve encountered while working on code that was written by someone else, in no particular order.

Respect Model/View/Controller.

Specifically views are responsible for their own layout and their own appearance. When controller code (or, God help you, model code) reaches into the innards of a view object in order to start rearranging the contents of the view object, then all sorts of horrors can ensue.

(In the code I just looked at, a UITableViewCell contains two images and three label objects. But the UITableViewCell is not responsible for laying its elements out; instead, the controller code which creates and populates the UITableViewCell is reaching in and moving the contents of the UITableViewCell around.

Why this is bad is because when the height of the view cell is later adjusted because it’s a non-standard height, you cannot simply respond to the layoutSubview method–as all the layout logic is contained in the controller code rather than in the table cell.)

When building complex table views or complex view layouts, consider drawing the view by hand.

On Android and iOS, scrolling a lot of views is expensive. Apple even notes this in their discussions about UITableViewCell. You are almost always better off (assuming your drawing code is fast) drawing the contents of the tableviewcell (or other elements of your user interface) rather than cobbling it together with a bunch of desecrate views.

Sometimes, of course, it’s easier to use a discrete view, and it’s not unreasonable to use a hybrid approach with a single image view added to a custom view which draws the other graphical elements.

On iOS things are a lot easier if you use a tool such as PaintCode, which automatically generates code for you.

Don’t subvert the standard way of doing things.

In the code I’m looking someone built a custom back button which looks almost exactly like iOS 6’s back button.

Guess what? In iOS 7 the back button looks totally different.

And as far as I can tell there was no need to build the custom back button at all.

(They haven’t tested this against iOS 7 yet. I sense pain and frustration.)

WordPong is out!

So now I can talk about the reason why I cared what the top 50 words in the English Language are (at least by looking at word frequency from various Project Gutenberg free books): WordPong on the Apple App Store.

The reason for the frequency is simple: in order to create a computer slider that goes from easy to hard game play, one thing I needed was a sorted dictionary of words, with the most often used words at the top of the list. Word frequency here is used as a proxy for word complexity: the more often a word is used, the more likely it will be familiar to younger members of the WordPong audience. And while I also use other parameter tweaks in order to simplify computer game play (such as how fast letters are picked by the computer and how likely the computer is to randomly flick a letter), word difficulty is one major aspect of the game.

It works quite well, by the way: at the first level the computer player limits itself to just the top 150 words in my sorted dictionary. At a middle level it’s restricted to the top thousand or so words: the theory being that the words should be almost instantly recognizable by the human player.