TaskLog 1.2 app update metrics

Another app update, another metrics post.

I just shipped TaskLog 1.2. This was a pretty major feature update – the largest in TaskLog’s history. As with the recent PuzzleTiles update, I thought I’d share some metrics about the app, and the update.

The previous shipping version of TaskLog comprised 3,388 lines of Objective-C code in 28 files (121 lines per file), plus 226 lines in C header files (8 lines per file). This is physical lines of code (SLOC), as counted by cloc.

The new updated version comprises 4,649 lines of Objective-C in 37 files (125 lines per file), plus 226 lines in 36 header files (8 lines per file).

Objective-C C Headers Total
TaskLog 1.1.2 28 files, 3,388 lines 26 files, 226 lines 54 files, 3,614 lines
TaskLog 2.0 37 files, 4,649 lines 36 files, 290 lines 73 files, 4,939 lines

The largest file was (and still is) the main view controller, TTMainViewController.m, which was previously 889 lines of code, and in the latest update is 1,085 lines of code.

In total, I spent 112.5 hours developing this update. Had I been working on it full time, I could have finished it in 3 weeks. Doing it part time, it ended up more like 6 weeks.

Notably (unlike the PuzzleTiles update), I added no Swift to TaskLog. It wasn’t really a conscious decision. I just did my thing, and when it was done, well, there was no Swift in there. I guess it didn’t really occur to me. TaskLog is several generations of code newer than PuzzleTiles, so it needed much less of an overhaul; maybe that was it.

On a semi-related note, I recently converted PuzzleTiles to Swift 2.0, and it took me two hours to straighten out all the code and make everything build and run properly once the Swift converter was done. Considering it has less than 600 lines of Swift code, that seems like a whole lot of effort. I’ve been working on an (as yet non-shipping) app for quite some time which is currently over 20,000 lines of Objective-C. It occurs to me that if it were written in Swift, I’d be in a world of hurt right now. I wonder if Apple isn’t updating Swift too, um, swiftly.

Accessing the *real* home folder from a sandboxed app

The preferred way to find a path for a directory within the user’s folder is to use NSSearchPathForDirectoriesInDomains (or an NSFileManager equivalent, such as URLsForDirectory:inDomains:). Problem with that is, if your app is sandboxed, these fuctions won’t give you paths the actual directories you’ve asked for, but rather the equivalent paths within your app’s container, even if you’re using entitlements which allow access to those paths.

So, let’s say you want to get the path for the user’s Documents directory. You’d end up with something like this:

- (NSURL*) getDocumentsDirectoryURL
{
    NSArray* paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
    NSString* documentsPath = paths[0];
    return [NSURL fileURLWithPath:documentsPath];
}

You might expect to get back something like file://localhost/Volumes/SSD/Users/zach/Documents/ (at least, you’d expect that if your name was Zach). But you might be surprised when you actually get something more like file://localhost/Volumes/SSD/Users/zach/Library/Containers/com.mycompany.myapp/Data/Documents/.

If you really want the path to the real Documents directory (in ~/Users/zach/Documents), you need to do something like this:

- (NSURL*) getDocumentsDirectoryURL
{
    struct passwd *pw = getpwuid(getuid());
    NSString* realHomeDir = [NSString stringWithUTF8String:pw->pw_dir];
    NSString* documentsPath = [realHomeDir stringByAppendingPathComponent:@"Documents"];
    return [NSURL fileURLWithPath:documentsPath];
}

Admittedly, there aren’t many cases where you would want to do this. One reason you’d do this is to set the default location for an open/save file dialog – navigating the user to the Documents directory in your app container would be quite confusing. In my case, VideoBuffet really wants to find all the movies in your Movies folder, and there of course aren’t any in the Movies folder equivalent of the app container.

Notably, if you’re doing something like getting the path to Caches or Library (say, to save some settings into a .plist), you definitely want to use the normal NSSearchPathForDirectoriesInDomains method, because those should be saved into the app conainer.

Update 05/11/17:This is still a valid thing to do today, and here’s how you’d do it in Swift 3:


func getDocumentsDirectoryURL() -> URL {
	let pw = getpwuid(getuid());
	let home = pw?.pointee.pw_dir
	let homePath = FileManager.default.string(withFileSystemRepresentation: home!, length: Int(strlen(home)))
	let documentsPath = (homePath as NSString).appendingPathComponent("Documents")
	return URL(fileURLWithPath: documentsPath)
}

Be careful with weak references

I’m working on an update to VideoBuffet. One of the changes is that movies are loaded on a background thread, to make the main UI responsive during loading. So I’ve a block of code in one of my view controllers that looks like this:

- (void) setCurrentPathURLs:(NSArray*)URLs
{
    [self moviesStartedLoading];

    __weak id weakSelf = self;
    [self.moviesDoc setMovieURLs:URLs completion:^{
        [weakSelf moviesFinishedLoading];
    }];
}

The little dance with a __weak reference is to avoid a retain cycle. The controller has a strong reference to moviesDoc, moviesDoc has a strong reference to the block, and because the block references self, it will have a strong reference to it. By making a weak reference to self, it won’t be retained by the block, and the cycle is broken.

I thought this was all good, until I did some sanity testing on 10.7 Lion, and discovered that it simply crashed when trying to open a movie. It didn’t take long to trace it back to the above code. Then I remembered this. Whoops, I’m making a weak reference to an NSViewController. Turns out that’s fine in 10.8, but not 10.7, according to the Transitioning to ARC Release Notes:

Note: In addition, in OS X v10.7, you cannot create weak references to
instances of NSFontManager, NSFontPanel, NSImage, NSTableCellView,
NSViewController, NSWindow, and NSWindowController. In addition, in
OS X v10.7 no classes in the AV Foundation framework support weak references.

The solution is to simply make it __unsafe_unretained, as in:

- (void) setCurrentPathURLs:(NSArray*)URLs
{
    [self moviesStartedLoading];

    __unsafe_unretained id weakSelf = self;
    [self.moviesDoc setMovieURLs:URLs completion:^{
        [weakSelf moviesFinishedLoading];
    }];
}

Really, though, the moral of the story is: test your app, on all OS’es it supports. If we hadn’t gone back and tested with 10.7, we’d never have discovered this, and we’d have ended up with many 1 star reviews.

Some objects don’t support weak references

Filed under “you learn something new every day”.

You can’t make a weak reference to an NSTextView (nor NSViewController, NSWindow, NSWindowController, and a few others). This was news to me.

The following code will not compile:

@interface MyWindowController ()
@property( weak, nonatomic ) IBOutlet NSTextView* textEntryView;
@end

You’ll get an error like this:

Synthesis of a weak-unavailable property is disallowed because it requires synthesis of an ivar of the __weak object.

Well, that’s not very helpful. If you manually add the backing iVar (which you should almost never do, just because there’s really no benefit), you get a more useful error.

@interface MyWindowController ()
{
    __weak IBOutlet NSTextView* textEntryView;
}
@property( weak, nonatomic ) IBOutlet NSTextView* textEntryView;
@end

Now the error is:

Class is incompatible with __weak references

OK, that makes more sense. Except, wait… what? Classes are incompatible with weak references? After a bit of digging I found this in the Resource Programming Guide:

Note: In OS X, not all classes support weak references; these are NSATSTypesetter, NSColorSpace, NSFont, NSFontManager, NSFontPanel, NSImage, NSMenuView, NSParagraphStyle, NSSimpleHorizontalTypesetter, NSTableCellView, NSTextView, NSViewController, NSWindow, and NSWindowController, and all classes in the AV Foundation framework.

In cases where you cannot therefore specify weak, you should instead use assign:
@property (assign) IBOutlet NSTextView *textView;

The (always useful) LLVM ARC guide has a section on weak-unavailable types which explains why:

It is explicitly permitted for Objective-C classes to not support __weak references. It is undefined behavior to perform an operation with weak assignment semantics with a pointer to an Objective-C object whose class does not support __weak references.

Rationale: historically, it has been possible for a class to provide its own reference-count implementation by overriding retain, release, etc. However, weak references to an object require coordination with its class’s reference-count implementation because, among other things, weak loads and stores must be atomic with respect to the final release. Therefore, existing custom reference-count implementations will generally not support weak references without additional effort. This is unavoidable without breaking binary compatibility.

So there you go.

If you want to follow me, I’m @zpasternack on Twitter and on app.net.

UIAlertView with UITextField, Revisited

My first ever blog post here was on putting a text field on a UIAlertView. While that technique still works perfectly fine, there is now (since iOS 5), an official API for putting a text field on an alert view. All you need to do is set the UIAlertView's alertViewStyle to UIAlertViewStylePlainTextInput. You can then access the text field using textFieldAtIndex:.

- (void) promptForName 
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Congratulations!" 
                   message:@"You earned a top score! Enter your name:" 
                  delegate:self 
         cancelButtonTitle:nil 
         otherButtonTitles:@"OK", nil]; 
    alert.alertViewStyle = UIAlertViewStylePlainTextInput; alert.delegate = self; [alert show];
}

- (void) alertView:(UIAlertView*)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    UITextField* nameField = [alert textFieldAtIndex:0];
    NSLog( @"You entered %@", nameField.text );
}

Of course, this also works with ZPAlertView.

- (void) promptForName
{
    ZPAlertView* alert = [[ZPAlertView alloc] initWithTitle:@"Congratulations!"
                    message:@"You earned a top score! Enter your name:"
                   delegate:self
          cancelButtonTitle:nil
          otherButtonTitles:@"OK", nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    alert.didDismissBlock = ^(NSInteger buttonPressed) {
        UITextField* nameField = [alert textFieldAtIndex:0];
        NSLog( @"Your entered %@", nameField.text );
    };

    [alert show];
}

If you want to follow me, I'm @zpasternack on Twitter and on app.net.

Taking advantage of the iPhone 5’s larger screen

Because it comes up on StackOverflow, I dunno, maybe five times per day, I thought I’d make a quick post describing how to make your apps work well with the new iPhone 5 screen dimensions (while still remaining compatible with older iPhones). It’s really not that hard at all. TaskLog had iPhone 5 support when it launched. It took me about 5 minutes to make this work, and probably a few additional hours to make it work well. The first step is to include an iPhone 5 specific default launch image. This is what iOS uses to determine whether or not your app is ready for the larger screen size. Iphone5 launch image It should be 640 x 1136 pixels. If you drag it into the Launch Images in Xcode, it will be automatically named for you. If you just add it to the project yourself, make sure you name it correctly: “Default-568h@2x.png”. Once you do this, your app will be sized to fit the iPhone 5 screen. From there, the amount of work you need to do depends entirely on how your application is built. If you’ve set up all your views with proper resizing characteristics (either via Auto Layout or the old-school autoresizing masks), you might be done. Just make sure to test it out in the Simulator (choose Device->Hardware->iPhone 5 (Retina) ) and make sure all your views look nice. I can’t stress this enough: test every one of your views on both 3.5″ and 4″ devices (or the simulator, at the very least). Places where you might have gotchas: if you’re doing any kind of hardcoding of coordinates, there might be some tweaking you need to do. If you’re going to move or size things in code, based on coordinates, at least try to do so via relative, rather than absolute, coordinates.

Related StackOverflow questions:

If you want to follow me, I’m @zpasternack on Twitter and on app.net.

Working around broken hiutil in Mountain Lion

For VideoBuffet, I use VoodooPad to author my help file. I learned about doing this from this blog post, and it’s been working well for me. Until the last VideoBuffet update, when suddenly my help anchors stopped working.

As the article states, you basically make a Run Script build phase in Xcode which exports the VoodooPad doc as HTML. Then, your VoodooPad doc is setup to run Apple’s help indexer (hiutil) to create the index. What the article doesn’t tell you is how to open your help to a particular page.

To do this, in VoodooPad you make an alias to the page to which you want to link, and give it a name (in the title bar, click Info; then, under Aliases, click the + button and type the name). The screenshot below shows VideoBuffet’s Preferences page, and you can see I’ve made an alias called “preferences”.

Voodoopad example

Finally, in code (like, in the Help button in the Preferences dialog), you can do this:

NSString *locBookName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleHelpBookName"];
[[NSHelpManager sharedHelpManager] openHelpAnchor:@"preferences" inBook:locBookName];

…and the appropriate page will open up in Help Viewer. It works great, and I use this technique all over the place.

Back to the point. While testing VideoBuffet 1.0.3, I discovered that the help links were all broken. After a bit of hair-pulling I finally figured out that hiutil was giving me errors, and ending up not creating a proper index (it wasn’t getting as far as my anchors). After Googling it, to no avail, I posted a question on Stackoverflow, which, at the time of this writing still has no responses. If you know the answer, by all means, post it there. :)

I’ve since discovered that the version of hiutil that ships with Mountain Lion (version 1.3) was where this problem started showing up, and the version from Lion (1.2) works as it always did. So, my (terrible) workaround: use the version of hiutil which shipped in Lion.

Find yourself a Lion system, and copy /usr/bin/hiutil to the machine where you do your builds. I didn’t want to replace the newer hiutil, so I called the Lion copy hiutil_old, and changed the VoodooPad export script to use that one. There’s one other step: hiutil 1.2 depends on MPWXmlCore.framework, which no longer exists in Mountain Lion. So in order to use hiutil 1.2 on Mountain Lion, you need to copy MPWXmlCore.framework from a Lion system as well (it’s in /System/Library/PrivateFrameworks/).

Update: Some folks on the original stackoverflow question I posted note that if you specify a doctype of XHTML 1.0 and fixup any obvious markup errors, Mountain Lion’s hiutil works fine. After messing about with my export scripts, I can confirm that this does appear to work (though, I’m not sure VoodooPad is really doing 100% valid XHTML). In any case, with some changes I’ve made it work.

I’ve also since upgraded to VoodooPad 5, and there are some tweaks I had to make to ensure everything still works. Specifically, exporting aliases to anchors works differently now. I’ll post another entry showing my updated workflow for using VoodooPad to author help files, soon.

If you want to follow me, I’m @zpasternack on Twitter and on app.net.

High resolution timing in Cocoa

For profiling app performance, it’s necessary to accurately time your code. The best way to do this is to use mach_absolute_time. In conjunction with mach_timebase_info, you can get extremely high resolution timing to ease performance benchmarking. I’ve wrapped this functionality up in a little class to make it super easy to use.

// MachTimer.h
#include <mach/mach_time.h>

@interface MachTimer : NSObject
{
    uint64_t timeZero;
}

+ (id) timer;

- (void) start;
- (uint64_t) elapsed;
- (float) elapsedSeconds;
@end

// MachTimer.m
#import "MachTimer.h"

static mach_timebase_info_data_t timeBase;

@implementation MachTimer

+ (void) initialize
{
    (void) mach_timebase_info( &timeBase );
}

+ (id) timer
{
#if( __has_feature( objc_arc ) )
    return [[[self class] alloc] init];
#else
    return [[[[self class] alloc] init] autorelease];
#endif
}

- (id) init
{
    if( (self = [super init]) ) {
        timeZero = mach_absolute_time();
    }
    return self;
}

- (void) start
{
    timeZero = mach_absolute_time();
}

- (uint64_t) elapsed
{
    return mach_absolute_time() - timeZero;
}

- (float) elapsedSeconds
{
    return ((float)(mach_absolute_time() - timeZero))
        * ((float)timeBase.numer) / ((float)timeBase.denom) / 1000000000.0f;
}

@end

You’d use it like this:

MachTimer* aTimer = [MachTimer timer];
[self performSomeOperation];
NSLog( @"performSomeOperation took %f seconds", [aTimer elapsedSeconds] );

I’ve used this code for iOS and Mac OS apps, and it works great.

If you want to follow me, I’m @zpasternack on Twitter and on app.net.

Retina Graphics in Mac OS X

I recently added Retina graphics to the Mac version of PuzzleTiles. I had Retina-ized TaskLog prior, and found that to be pretty trivial, as it’s not a very graphics-heavy app. PuzzleTiles has many hundreds of images, so it was a bit more of a challenge. The whole process is pretty straightforward, especially if you’ve done Retina graphics for an iOS app. The TL;DR is: * Make double-size images and suffix them with @2x * Use NSImage imageNamed: to load them * Use Quartz Debug to test your new graphics (if you don’t have a Retina MacBook Pro)

The code

The main thing is to use NSImage imageNamed:
It does all the @2x image-loading magic. One thing not immediately obvious to me is that you don’t specify the extension when doing so.

NSImage* myImage = [NSImage imageNamed:@"foo.png"];  // NO, this makes the magic not work.
NSImage* myImage = [NSImage imageNamed:@"foo"];      // YES, magic is a-comin'.

The art

Producing @2x artwork was, by far, the biggest task. Luckily we’d had the foresight to make all our source art with vector graphics (text, shapes, and effects layers) which are basically arbitrarily resizable. The first step was batch upsizing everything to 2x. I ended up making a separate set of source art for our @2x images, so that we could tweak them by hand. Some of the artwork we upsized with no other changes, but for some of them we wanted to tweak some things: line or shadow thickness, for example. Some others (the Wood tile set, for example) had bitmaps which we had to completely redo. My advice is this: if your source art isn’t vector-based, it might be time to bite the bullet and do that. If you’re like me and don’t have a graphic artist on staff to do all this stuff for you, I have a few pieces of advice to ease the Retina-izing process:

  • Get familiar with PhotoShop’s automation tools (File->Automate->Batch and File->Scripts->Image Processor). This saved me tons of time when converting, resizing, and exporting hundreds of images at once.
  • Get a tool for batch file renaming. At one point I decided to change my file naming convention (to make things more amenable to using imageNamed:), and hand renaming nearly a thousand files would have been a time-consuming, error-prone task. I ended up using Core-Renamer for this, and though the UI is a little bit wonky, it worked perfectly.

Testing

If you don’t have a Retina MacBook Pro, you can use any old Mac to test out your Retina graphics. Download and install Graphics Tools for Xcode (from within Xcode, choose Xcode->Open Developer Tool->More Developer Tools). Run Quartz Debug, choose Window->UI Resolution, and check “Enable HiDPI display modes”. Now, when you go to Displays in System Preferences, you’ll see a bunch of HiDPI modes. Pick one, run your app, and see how it looks.

References

The WWDC 2012 session “Introduction to High Resolution on OS X” is fantastic; I highly recommend checking that out.

If you want to follow me, I’m @zpasternack on Twitter and on app.net.