Transitioning to iOS7

A lot of people are taking the plunge, like it or not, into iOS7 “optimized” apps. Some folks were going to take their time and transition slowly but Apples recent announcement to developers that February was it and that like it or not they HAD to build iOS7 apps by February has pushed timelines into hyperdrive.

Here are a few useful things I’ve learned along the way that might may others transition to iOS7 a little easier:

1. iOS7 or not
This little bit of code

if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1)

can easily detect if you’re running on iOS6.1 or older. Of course the opposite is also true. You can use this code

if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1)

can detect if you’re running on iOS7 or newer. Very helpful if you want to keep your old code in place, to look nice for your customers running iOS6.1 or older.

In case you have to continue supporting iOS6 / Xcode 4 then creating the following header file

#ifndef PK_Xcode4_support_h
#define PK_Xcode4_support_h

#ifndef NSFoundationVersionNumber_iOS_6_0
    #define NSFoundationVersionNumber_iOS_6_0  993.00

#ifndef NSFoundationVersionNumber_iOS_6_1
    #define NSFoundationVersionNumber_iOS_6_1  993.00


will ensure that your code behaves properly when compiled with Xcode 4 or Xcode 5. By the way a quick look in NSObjCRuntime.h will confirm that both NSFoundationVersionNumber_iOS_6_0 and NSFoundationVersionNumber_iOS_6_1 are supposed to be defined as 993.00.

2. Mind the gap
One of the new features of iOS7 is that your views can slide under the navigation bar. If you want to do this on purpose then more power to you but if you’re just trying to get your app to look reasonable then this little bit of code

if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
    // Setting traslucent make sure that the view doesn't slide under in iOS7
    self.navigationController.navigationBar.translucent = NO;

3. Wrapping table cells
Some code relies on the fact that the superview of a UITableViewCell to be a UITableView. This is no long true under iOS7. As of iOS7 UITableViewCell superview is actually UITableViewCellScrollView (which is so to support sliding table cells for delete etc). In general it’s probably a bad idea to depend on the view hierarchy (Apple can and does change it) but if you’re going to this little bit of code

id cellSuperview = [cell superview];
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
     cellSuperview = [cellSuperview superview];

will do the trick. cellSuperview should, at the end of this code, point to the UITableView that the cell lives in.

4. Popovers
One problem that became apparent very quickly, as I was transitioning code to iOS7, is that UIPopoverController‘s we’re a very happy bunch. All of the popovers looked wrong. After much digging and searching I discovered that iOS7 UIPopoverControllers looked at the contents preferred content size. To that end I wrote this method

- (void)setContentSize:(CGSize)contentSize animated:(BOOL)animated{
    if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
        CGSize size = contentSize;
        if (size.width == 0){
            size.width = 320;
        if ((size.height == 0) || (size.height == 44)){
            size.height = 1100;
        [self.contentViewController setValue:[NSValue valueWithCGSize:size] forKey:@"preferredContentSize"];
    } else {
        [self setPopoverContentSize:contentSize animated:animated];

in a category class for UIPopoverController. This code checks if we’re running under iOS7 or 6. If we’re running under iOS7 it looks at the size being passed in. The code assumes that the argument contentSize is from a call to the contents UIViewController method contentSizeForViewInPopover. Under iOS7 this method has been deprecated and returns width=0 and height=0. Previously this method would have returned width=320 and height=1100. This category method then sets the size back to the original default and then sets the preferredContentSize of the contentViewController so that the UIPopoverController will once again be happy.

5. Searching Popovers
One problem I came across, which is less of an iOS6 to iOS7 problem and more of an iOS7 to iOS7.1 problem, is searching in popovers. There seems to be a problem with the search view not properly managing the search view. The result is that as you type and get results for the search the view overwrites the underlying view BUT the underlying view remains active. This is a serious mess. So far I haven’t found a good answer other then using iOS7.1. Apparently this is a good solid iOS7 SDK bug that Apple has fixed. As of yet I haven’t found a good backwards fix.

Well, that’s all for now. As I discover more of the tips I’ll post the.

Associative References

If you’ve been developing with Objective-C for a while you know it’s powerful stuff. While it’s not as elegant looking as some languages, such as Ruby, it does have a rather impressive array of features that make it just flexible as new languages, such as Ruby.

One of the flexible features of Objective-C is Categories. Categories allow developers to snap on methods to classes they didn’t create and don’t have access to their source code. Beyond that, these methods become part of the class hierarchy.

One complaint that I’ve had with Categories is that you can’t add properties as part of the category snap on. Recently I wanted to extend UITextView so that it would be easier to take advantage of AttributesStrings. My first thought was to create a Category and initially it seemed I was on the right track. That was, until I realized that I wanted to have the UITextView keep track of default fonts. Default fonts mean properties and properties mean so long Category … or does it?

After building a subclass of UITextView, to do the things I want AND adding new properties, I wasn’t happy with the way thing looked. It’s not that the code wouldn’t do it’s job but it just didn’t feel as clean as it could be. I tried to improve my code by splitting off some capability into a Category.

As I wrote the Category it just felt right so I started trying to move the rest of my code into the category but still there were these properties. A little research on the net turned over something new, Associative References.

Associative References make it possible, like Categories, to attach (or associate) an object instance variables to an existing class and as the French would say “et voila” there you go, Categories with Properties.

Ok, so how do you make use of Associative References? First stop is to add properties to your Category:

@interface UITextView (Utilities)

@property (nonatomic, strong) UIFont *regularFont;

Now, Xcode will complain that since this is a category you’re going to have to implement the getter and setter for this property. So let’s get to implementing:

#import <objc/runtime.h>

static void *RegularFontKey;

@implementation UITextView (Utilities)

- (UIFont *)regularFont{
    return objc_getAssociatedObject(self, &RegularFontKey);

- (void)setRegularFont:(UIFont *)regularFont{
    objc_setAssociatedObject(self, &RegularFontKey, regularFont, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

Lines 7-9 and 11-13 are the methods that addresses Xcodes complaint. Pretty boiler plate. The magic happens on lines 8 and 12. Line 12 sets the value of the property and line 8 gets the value of the property. In both cases you’ll notice the use of the void pointer from line 3. This is a key that makes the association possible and it needs to be unique per property  and per class but not per property. This means that a developer simply has to replicate the pattern in line 3 per key.

In general, I would say simply replicate the pattern laid out in the code above to add properties to a category.

Happy Hunting

Finding the words

Recently I was challenged to build some code that could brake up an NSString into an array of NSStrings that would fit into a given width in an iOS app. Seems fairly straight forward, given that Apple has it in their text GUI elements. No dice my friends. While Apple does give you the ability to discover the dimensions of an NSString given a UIFont and, optionally, some size constraints it wont tell you how to break up the NSString into the individual lines.

So, what is one to do? Time to replicate some existing Apple capability. The basic idea is to split up a string into words, then build a line by adding a word at a time until it’s too long, then repeat until you’ve run out of tokens.

Splitting a string into words isn’t easy. My first stop was to use ParseKit. It’s a nice fast parser for Objective-C but it seems to have lost its support and hasn’t been updated in some time. The fact that it hasn’t been updated in a while made it a bit harder to integrate into the project. After a bit of pushing and pulling I managed to stuff it into the project.

Over all the ParseKit worked well enough and its compiled library wasn’t particularly big but it was a pain to install and has quiet a few warnings. I ended up fixing a bit of code and also adding a bunch of warning suppression so that I could work in peace.

I got the code to work but I wasn’t happy with all the extra code that was hanging around to make ParseKit work. So it was back to the drawing board. I dug around the net but didn’t find anything that I was happy with, time to reinvent the wheel.

What I ended up doing was making use of Objective-C regular expression engine, NSRegularExpression, and hand built a regular expression.

    NSMutableString *regexPattern = [NSMutableString string];
    // A number or dollar amount
    [regexPattern appendString:@"(\\$?\\d+(\\.\\d+)?)"];
    // or
    [regexPattern appendString:@"|"];
    // possibly starting with a quote, a word, possibly trailing by punctuation
    [regexPattern appendString:@"\\\"?([\\w\\']*)(\\.\\.\\.|\\.|,|-|!|\\?|:|;|\\\")?"];
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexPattern options:NSRegularExpressionCaseInsensitive error:&error];

Lines 3,5, and 7 or the different parts of the regular expression I built to parse words. Line 3 matches numbers as well as dollar values. line 5 is a simple ‘or’, and line 7 matches a word, consuming the leading quote if there is one, consuming trailing punctuation if that exists. The rest of the code in that method simply builds an array of all the tokens.

Here is the full code for turning a string into an array of words:

- (NSArray *)stringToWords{
    NSMutableString *regexPattern = [NSMutableString string];
    // A number or dollar amount
    [regexPattern appendString:@"(\\$?\\d+(\\.\\d+)?)"];
    // or
    [regexPattern appendString:@"|"];
    // possibly starting with a quote, a word, possibly trailing by punctuation
    [regexPattern appendString:@"\\\"?([\\w\\']*)(\\.\\.\\.|\\.|,|-|!|\\?|:|;|\\\")?"];
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexPattern options:NSRegularExpressionCaseInsensitive error:&error];

    NSArray *matches = [regex matchesInString:self
                                        range:NSMakeRange(0, [self length])];
    NSMutableArray *tokens = [NSMutableArray array];
    NSUInteger endOfLastToken = 0;
    for (NSTextCheckingResult *match in matches) {
        NSRange matchRange = [match range];
        if (matchRange.location != endOfLastToken){
            NSRange tempRange = NSMakeRange(endOfLastToken, matchRange.location - endOfLastToken);
            [tokens addObject:[self substringWithRange:tempRange]];
        [tokens addObject:[self substringWithRange:matchRange]];
        endOfLastToken = matchRange.location + matchRange.length;

    return tokens;

And here is the full code for using that array of tokens to an array of lines:

- (NSArray *)linesConstrainedToWidth:(CGFloat)maxWidth withFirstLineIndent:(CGFloat)indent andFont:(UIFont *)font{
    CGSize maxSize = CGSizeMake(maxWidth - indent, FLT_MAX);

    NSMutableArray *strings = [NSMutableArray array];
    NSMutableString *newString = [NSMutableString string];
    NSMutableString *oldString = [NSMutableString string];

    NSArray *tokens = [self stringToWords];
    for (NSString *token in tokens){
        //NSLog(@"(%@) (%.1f) : %@", token.stringValue, token.floatValue, [token debugDescription]);
        [newString appendString:token];
        CGSize size = [newString sizeWithFont:font constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap];
        if (size.height > font.lineHeight){
            [strings addObject:oldString];
            newString = [NSMutableString stringWithString:token];
            maxSize = CGSizeMake(maxWidth, 2000.0);
        } else {
            oldString = [NSMutableString stringWithString:newString];
    [strings addObject:newString];

    return strings;

As you can see this method allows you to constrain the line to a specific width as well as setting a first line indent, just in case.

Warning be gone

In a previous post I talked about getting clang to be quite, ie every once in a blue moon you want a warning to simply go away. As I said, I’m really not a big fan of doing this, a warning usually means that something is wrong and you should fix it and not just ignore it.

For that once in a blue moon event I’ve got more detail on how to turn the warning suppression from a blunt instrument to a nice precision surgical instrument.

Inserting the following line in your code will suppress ARC performSelector warnings.

#pragma clang diagnostic ignored "-Warc-performSelector-leaks"

If you add a little more code

#pragma clang diagnostics push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
// code  that needs a warning suppressed
#pragma clang diagnostics pop

You limit the impact of the suppression to just the bounds of the push and pop.

Of course the next part of the magic act is to figure out what exactly is the warning you want to suppress. Xcode does a fantastic job of giving you the human readable version. It actually gives you a running start before you slam into the brick wall. The problem is that there doesn’t appear to be a very good/complete list of human redable warnings and their official flag counterparts. So, what is one to do now?

Turn out that if you’re willing to peal away a layer of Xcode you can find the actual warning flag. Start by compiling your code, which will bring up the warning. Next, press Apple-7. This will bring up the Log Navigator. Click on the top log and scroll down until you find your warning. Click the detail button, its the rounded button with a set of horizontal lines. Now you see behind the Xcode curtain and see the gory detail. The top part of the details is the exact command used to compile your problem file. The bottom part gives you the details of the warning. If you examine the warning you’ll see that the ling ends with a [-Wwarning]. That’s it. This is the flag you want.

This is where I found info about the warning suppression push and pop ‘Disabling Clang Compiler Warnings’

Objective-C Duck Punching

Objective-C is a cool language for many reasons. One reason is that it’s a dynamic language that allows you to do all kinds of fun things at runtime. Allas one of those features has gone away with the introduction to ARC.

Once upon a time you could send any message you like to an Objective-C object and it would try to respond. If you inherited from NSObject you could make use of the invocationForwarding method to handle any method you didn’t expressly implement. Over time the compiler got smarter and wouldn’t let you send just any message to Objective-C objects so you had to switch to using the id type. id would catch anything. This is no more.

I came across this thread ARC: error: no known instance method for selector. One of the contributors to the thread, John McCall of Apple, made the following statement:

Our reasoning was split about 50/50 between (1) needing to be more careful about types and ownership and (2) wanting to eliminate an embarrassing wart in the language (not being allowed to complain about completely unknown methods with anything more strenuous than a warning).  There is really no legitimate reason to call a method that's not even declared somewhere.  The ability to do this makes some really trivial bugs (e.g. typos in selectors) runtime failures instead of compile failures.  We have always warned about it.  Fix your code.


You can follow the whole thread but the short is that Apple made the call to be more cautious about types and ownership and traded away the flexability of id. Is this the end of the world? Nah, it just takes out a nice little quirky feature of the language.

Telling clang to be quiet

When using Xcode I’m a big believer in clearing out not just the error messages that I get but also all the warnings. 99% of the time if I ignore a warning it usually results in something crashing or a weird bug expressing itself. BUT there is that 1% of the time when Xcode produces a false positive and you get a warning that isn’t and all you want to do is make it go away. Today was such a day and thankfully I found how to tell clang to ignore the warning.

I have some code:

[component performSelector:componentSelector];

clang really doesn’t like this code. The problem is that ‘componentSelector’ is a variable and clang doesn’t have a enough information about it so it raises a flag about possible memory leak. Now, I know, since I wrote the code, that ‘componentSelector’ is good and won’t cause a memory leak so to silence the warning I add the following:

#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[component performSelector:componentSelector];

this is a very nicely specific flag telling clang to ignore the performSelector leaks warning. I’d really rather find away around this, ie making clang happy, but thus far no luck so it’s the ignore flag till I do.

The Literals are Coming, the Literals are Coming

It’s just days before WWDC and the rumors are flying about what Apple will introduce. Will it be iOS 6? new iPhone hardware? MacBook Pros? how about Mac Pros? One addition that isn’t actually a rumor but pretty much a confirmed fact is the addition of literals to Objective-C and the arrival of the Apple LLVM compiler.

The cat escaped the bag back in March when Apple checked in code to the open source clang trunk, over at, adding capabilities to make literals possible. Along with checking in the code came some very nice documentation that details what literals mean for developers. The Big Nerd Ranch Weblog followed the release by Apple with a slightly shorter explanation on literals.

If you have the time I would definitely recommend reading the article. The short version on literals is that Apple is bringing some of the comforts of Ruby to Objective-C by extending the responsibilities of the ‘@’ symbole. The slightly longer version is the Apple is adding syntactical sugar to NSNumber, NSArray, and NSDictionary.

For NSNumber Apple has simplified the process of creating them. You can now prepend a number with the ‘@’ symbol and presto, you’ve got an NSNumber object. There isn’t an equivalent way to get your number back out of NSNumber but this is definitely a good start.

For NSArray and NSDictionary Apple has added a bit of magic too. Now you can create an NSArray by putting your array inside a ‘@[]’ and an NSDictionary by putting your dictionary inside a ‘@{}’. Unlike NSNumber Apple added a nice way to get data back out of both NSArray and NSDictionary. The secret is ‘[]’. You put square brakets after either your NSArray or NSDictionary and then put your index, either number or object, inside the square brackets.

If you’re feeling particularly adventures you can download the current build of both llvm and clang from Unfortunately at the moment Xcode doesn’t have these new features but wait a moment, well at least until Monday, and you’ll have Objective-C with Literals.

clang, It’s not just a Objective-C compiler frontend

One of the things I discovered while investigating building my own programming language was the fact that clang is much more then your typical front end to the llvm compiler. It turns out that clang can do all kinds of useful things for you if you’re trying to build your own C/C++/Objective-C IDE. Closer inspection of clang reveals that it can do all kinds of wonderful things like code completion, pointing to specific lines where you have coding mistakes, and much more. It’s a fantastic treasure trove of tools.

If you’re interested in learning more I would highly recommend taking a look at Doug Gregor’s LLVM Developer Meeting presentation titled “libclang: Thinking Beyond the Compiler” (slides/video) It’s a great presentation and it will get you on your way to building your own IDE or at least giving it some serious thought.

A Little Insperation

Every now and than I come across some good inspiring video. Not too long ago I came across this video of the winner of the Moth GrandSLAM. The main guy talking is Moran Cerf, an Israeli, and he gives a very engaging talk about his background and the story that led him to becoming a researcher.

All in all this is a great video and well worth the 10 minutes.

A Little bit of Mobile History

For the longest time I’ve been a fan of mobile computer. It started with devices like the Newton and RIM and now I’m building mobile apps for Android and iOS. Along the way I’ve had the fortune of watching history being made. One company that seem to have a very bright future was Palm.

In the beginning Palm was revolutionary for all the things it didn’t do. While the Newton tried to be a portable computer, Palm focused on phone numbers, calendars, etc. It didn’t try to do handwriting recognition but instead invented a new, simpler, letter set. With the introduction of the Palm V the Palm got sexy. Palm had the good sense to pair up with IDEO and the result was a thin PDA that people wanted to own.

Between then and now something happened. Actually quiet a bit happened. At one point an acquaintance moved his family out to CA so he could work for Palm. When I spoke with him about what was coming down the pipe he went on and on about the web and building on the web. At the time I didn’t quiet understan what he was going on about but then I saw webOS and the light went on.

I was impressed, the concept/implementation made sense and a moment later the company was snapped up by HP. I thought that HP saw the light too but the next moment HP decided to kill webOS and just as quickly webOS decided to open source webOS. Now, it’s all dead. The webOS team migrated to Google and it seems that the open source webOS is on the fast track to NO WHERE.

I got the chance to write some code for the HP TouchPad and it wasn’t half bad. It seemed like a fun platform that basically needed more work but had lot of potential. The Linux base made an interesting platform and I was looking forward to understanding webOS better.

All of this is a very long way of pointing to a rather interesting article written by the guys over at The Verge called Pre to postmortem: the inside story of the death of Palm and webOS. It details the ins and out/ups and downs of Palm/webOS. It’s well written and worth the time.