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.

Posted in Uncategorized | Leave a comment

Dear WordPress

Thanks (NOT!!!) for letting me know of all the messages in the queue waiting for approval–including comments that I made months ago.

(Shakes head)

There are days when I want to build my own blogging system, just so I can bypass all this weirdness.

Posted in Uncategorized | Leave a comment

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.

Posted in Uncategorized | 1 Comment

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…

Posted in Uncategorized | 1 Comment

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.”


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.

Posted in Uncategorized | Leave a comment

Things to remember: resize icon script for iOS

On iOS there seems to be about a billion different icon sizes, depending on if you’re on iOS 7 or iOS 6, on iPhone or iPad, or for search icons or whatever.

This is a script which I created to help automatically resize all the icons that are used.

if [ $# -gt 0 ]; then
    sips $1 -Z 29 --out icon-29.png
    sips $1 -Z 58 --out icon-29@2x.png
    sips $1 -Z 40 --out icon-40.png
    sips $1 -Z 80 --out icon-40@2x.png
    sips $1 -Z 50 --out icon-50.png
    sips $1 -Z 100 --out icon-50@2x.png
    sips $1 -Z 57 --out icon-57.png
    sips $1 -Z 114 --out icon-57@2x.png
    sips $1 -Z 60 --out icon-60.png
    sips $1 -Z 120 --out icon-60@2x.png
    sips $1 -Z 72 --out icon-72.png
    sips $1 -Z 144 --out icon-72@2x.png
    sips $1 -Z 76 --out icon-76.png
    sips $1 -Z 152 --out icon-76@2x.png
    echo "Done."
    echo "You must provide the name of an image file to process."

To use, in the terminal execute this script with the name of the .png file to be resized, and this will generate all the different icon sizes used.

Posted in iphone | Leave a comment

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.

Posted in Uncategorized | Leave a comment

How to suck down iOS memory without even trying.

If you build custom UIView or UIControl objects, it’s important to remember that all of your views are backed by a CALayer object, which is essentially a bitmap image of the rendered view object. (This is how iOS is able to very quickly composite and animate views and images and the secret behind iOS’s UI responsiveness.)

However, this has some consequences on memory usage.

For example, if you create a view which is 2048×2048 pixels in size (say you are scrolling through an image), and you don’t switch the backing layer to a CATiledLayer object, then for that view iOS will allocate 2048x2048x4 bytes per pixel = 16 megabytes for the CALayer backing store. Given that the memory budget for the backing store on a small device (such as the previous generation iPod Touch) is only about 8 megabytes, your application will die an ignoble death pretty quickly.

Now not all views are the same. If you create a view that is 2048×2048 pixels in size, you set the background color to a flat color (like ‘gray’), but then you don’t respond to the drawRect method to draw your view’s contents, then the backing store in CALayer is very small. (Internally I believe iOS is allocating odd-sized texture maps in the graphics processor–and if the view is a flat color the graphics processor allocates a single pixel texture and stretches it to fit the rectangle. Also if you’re setting the background to one of the predefined textures, I believe it’s not allocating any memory at all, but instead setting up a texture map from a predefined texture and setting the (u,v) coordinates to make the texture fit.)

(An empty view, by the way, can be useful for laying out the contents inside that view; just respond to layoutSubviews, grab the bounding rectangle, and do some rectangle math to lay the contents out.)

So if you need to create a large container view with a border around it, you may be better off allocating two UIViews: one with the background color inset a pixel from the other view which is the border color. Otherwise, the moment you invoke drawRect to draw the frame, on an iPad with a retina display your container view–if it fills the screen–will require 2048 x 1536 x 4 bytes per pixels = 12 megabytes, just to represent a bordered container.

(Footnote: I have a feeling CAGradientLayer is doing something behind the scenes to cut down on memory usage; otherwise why have this class at all? And if that’s the case, in the event where you need to populate a bunch of controls over a background with a subtle gradient effect, you may want to use this as your view’s backing store rather than overriding the drawRect method and filling the entire view with a gradient.)

Posted in iphone | Leave a comment

Wrapping text with ellipsis on iOS

This is an extremely common pattern I encounter quite a few times, and worthy of it’s own “things to remember” post.

So you want to have some text which wraps, but when it hits the bottom of the window, you get an ellipsis, right? But [NSString drawInRect…] doesn’t do the trick, right?

Well, it turns out the answer is using an NSAttributedString.

The first step is to turn your label string into an attributed string. At this point you need to know the font and color of the text that will be rendered, so you need to bake these attributes into the string. So, for example:

- (NSAttributedString *)attributedStringWithString:(NSString *)str
	UIFont *font = [UIFont boldSystemFontWithSize:19]; /* Some font */
	UIColor *color = [UIColor blackColor]; /* Some color */
	NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
		font, NSFontAttributeName,
		color, NSForegroundColorAttributeName,
	return [[NSAttributedString alloc] initWithString:str attributes:d];

The next step is to draw the string in the rectangle area where it belongs:

	NSAttributedString *astr = [self attributedStringWithString:self.myLabel];
	[astr drawWithRect:r
		options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine

And this will wrap the text, truncating the last line with an ellipsis.

The advantage of using NSAttributedString is that you can also easily insert segments of text which are of a different color or style. I find it easiest to build up the attributed string through concatenation of attributed segments into an NSMutableAttributedString object. So, for example, if you’re displaying a tweet from Twitter and you wish to bold all the hashtags, you simply parse the string (scanning for sequences staring with whitespace and a ‘#’, and including all the alphanumeric characters past the ‘#’), and create an attributed string of that segment as bold, concatenating all the strings into a single mutable string.

And for optimization purposes you can then hang onto the attributed string rather than the original string.

Posted in Objective C++, Things To Remember | Leave a comment

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.)

Posted in Uncategorized | Leave a comment