Archive of articles classified as' "Cocoa"

Back home

Objective-C Tricks: Scope your Assignments


There’s a new Objective-C pattern I’ve been experimenting with lately, which looks like this:

This syntax probably isn’t familiar to Objective-C programmers, but it’s actually simple. It’s a trick that takes advantage of a compiler extention where putting a variable by itself as the last line within () braces acts as “returning” that variable, meaning you can use the whole expression as an assignment.

What’s the point? Chances are you’ve worked on an iOS app or two where some big controller class had a viewDidLoad method that’s grown out of control. The kind of class that’s managing a dozen views, each with their own content, setup, positioning and so on. In these classes the viewDidLoad method can be hundreds of lines long, impossible to quickly read and parse, and require refactoring for even small changes.

The advantage of this syntax is that it wraps each assignment into a neat little bundle, no matter how much extra work is related to it. Temporary variables, subviews, configuration and whatnot all live within the scope’s braces, so it’s easy to see at a glance what code belongs to each specific object. You can give temporary variables nice names too, since they all live within their own scope. Ever have a method where you have to name things like passwordFieldFrame, confirmPasswordFieldFrame, …? Now each of those CGRects can just have the nice, short name “frame” without worrying about stepping on the toes of another object.

There’s an argument to be made against this syntax, and I’m not completely sold on the idea. In an ideal world you’d want to split these view controllers into more managable subcontrollers, instead of trying to pretty up the mess. It’s also a little hacky, relying on a language feature that’s not intended for this purpose. But despite these problems I still kind of like what it does. It’s hard to say no to anything that makes code more manageable and easy to read.

No Comments



If you’re the type of developer who’s always digging into the Cocoa frameworks to find the stuff that makes your life easier, you’re probably using NSCache. It’s a great class after all. Just store your temporary objects in an NSCache instead of an NSMutableDictionary, and you won’t have to worry about memory usage. Right?

Not exactly. A recent conversation on Twitter reminded me of my own experiences working with NSCache and memory warnings. Although it’s natural to expect NSCache to clear itself in response to a memory warning notification, this isn’t what actually happens. NSCache does automatically evict objects, but this behavior is very unclear and undocumented. In short, don’t depend on it. It’s possible for your app to receive memory warnings, and even crash due to low memory, all without NSCache lifting a finger to help. Instead, keep doing what you’ve always done. Register for low memory notifications and manually release any objects that aren’t essential, whether they’re stored within NSCache or otherwise.

There’s nothing wrong with using NSCache, but until the docs say otherwise don’t count on it to do the work for you.

No Comments

On iCloud Syncing


If you follow the Cocoa development community you probably know how big of an issue iCloud syncing is. Watching the WWDC videos from last year you might think iCloud is the next big thing in Cocoa, much like Bindings or Core Data. It’s only when you start really looking at it in depth that you realize just how many bugs and edge cases you have to account for. Trying to enable Core Data iCloud syncing is a huge undertaking for advanced developers, and even the more reliable document and key value store syncing can have its share of problems.

More and more developers have started down the iCloud path and realized too late what the actual issues are. Some have updated their apps to remove iCloud support, and others are not even shipping until Apple fixes some of the problems they’ve run into. I’m definitely part of this crowd with some of my apps I had hoped to ship last year. I started with Core Data before I decided it wasn’t worth the risk and moved my app to document based data storage. Even now I’m not sure I’m on the right track though. My app has a very simple data model, but even after putting in a good amount of work and re-writing things two or three times there’s still work to do.

There are other solutions, including open-source sync frameworks like TICoreDataSync, and Dropbox’s new Sync API. Some of these look quite promising, but in the end it’s impossible for any third party library to achieve the same simplicity and support iCloud promises. I’m hoping Apple realizes just how many developers are affected and is working to improve things. It’s clear that this is hurting the Mac OS and iOS software ecosystem, and if even if some of the problems are resolved it will be hard getting developers to trust iCloud when there are so many horror stories out there.

No Comments

Seven Deadly Sins of Modern Objective-C


I’ve had this post cooking for a long time, and I think it’s ready to unveil. If you code Objective-C, this is going to offend you and that’s good. If you aren’t offended, then you don’t care, and that’s bad.

This list isn’t about stylistic things like which line new braces go on (new ones, duh). This list is about potential problems with the code you’re writing on an objective scale. So let’s get started.

Read more on Ash Furrow’s blog. I admit, I’m guilty of a few of these. Hopefully number seven, not using automated testing, will soon be crossed off my list. I’ve experimented with it in the past, but still haven’t adopted it on any of my shipping Cocoa projects.

No Comments

UIImage Category Methods


If you’ve Googled about resizing or cropping UIImage objects, chances are you’ve read Trevor Harmon’s blog post on the subject. Trevor’s solution is great, but unfortunately a little dated since changes to the iOS SDK have introduced a few bugs and compiler warnings if you try to use the original code written in 2009.

I’ve been maintaining my own copy for the past year or so, and I’ve finally gotten around to open sourcing it on GitHub. This fork includes a few of my own changes and bug fixes described in the comments of the original post. If you need to resize or crop an image check it out!

1 Comment

Tutorial: Disable the iPhone 4′s Front Camera


I’ve been negligent in posting new articles this year, but despite appearances this blog isn’t quite dead yet. I’ll begin regular postings again soon, but in the meantime here’s a link to an article I guest authored over at iCodeBlog:

One option is to replace the standard camera controls with a custom interface, but that’s a whole lot of work if you just want to prevent the user from taking a photo with the front camera. Fortunately there’s another option: put a transparent button over the “switch camera” button, which will intercept touch events and show an alert dialog. It sounds simple, but as you’ll see there are a few tricks to actually getting this to work.

Check out the rest here!

No Comments

Restart your Cocoa application using Sparkle


It’s not uncommon for an OS X application to need to restart itself in certain unavoidable situations, such as hiding the dock icon. Most of the solutions you’ll find on the Internet rely on a command line helper app that waits for the parent application to finish exiting before launching it again. Although this isn’t hard to implement yourself, chances are you already have everything you need, buried inside the Sparkle framework.

Based on the Sparkle source code, here’s a quick way to restart any application that includes the Sparkle framework.

NSString *launcherSource = [[NSBundle bundleForClass:[SUUpdater class]]  pathForResource:@"relaunch" ofType:@""];
NSString *launcherTarget = [NSTemporaryDirectory() stringByAppendingPathComponent:[launcherSource lastPathComponent]];
NSString *appPath = [[NSBundle mainBundle] bundlePath];
NSString *processID = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]];

[[NSFileManager defaultManager] removeItemAtPath:launcherTarget error:NULL];
[[NSFileManager defaultManager] copyItemAtPath:launcherSource toPath:launcherTarget error:NULL];
[NSTask launchedTaskWithLaunchPath:launcherTarget arguments:[NSArray arrayWithObjects:appPath, processID, nil]];
[NSApp terminate:sender];

If you’re not using Sparkle, here’s a complete implementation of this idea you may find helpful.

1 Comment

Brent Simmons on Core Data


Brent Simmons has an interesting write-up on his experience with Core Data on NetNewsWire for the iPhone:

At that point, having done everything else, the remaining issue was clearly Core Data. So I tried more things, re-read everything I could about Core Data performance (for the nth time), ran experiments, spent tons more time in Shark. Trying to get it good. No go.

Finally I realized I had to switch away from Core Data and use SQLite more directly. Not completely directly — I use FMDB, a lightweight Objective-C interface that works on Macs and iPhones. Gus wrote it. It’s good.

A good introductory read on the differences between Core Data and SQL storage is Matt Gallagher’s article, which Brent also mentioned.

No Comments

Snow Leopard for developers


Today is Snow Leopard day, and unlike many other developers I’ve waited to buy it in stores instead of installing an ADC development seed. This means I’ve been mostly in the dark about any API changes or new developer tools in 10.6, aside from what I’ve managed to coax out of the guys at the local Syracuse CocoaHeads meetings.

To give myself something to do while waiting for my pre-install backup to finish, I’m going to update this post on any good articles or write-ups on what’s new in Snow Leopard for developers. If you’ve written or seen anything that I should include here, please leave a comment!

  • Tim Wood gives a great roundup of the major (and not so major) new developer features in Snow Leopard.
  • Andy Matuschak talks about associated objects, which allow you to add instance variables to any class which descends from NSObject.
  • Twitter has plenty of 10.6 tips from developers today. In particular, you probably want to follow Cocoa Dev Central.
  • Mike Ash has a great write-up on the basics of Grand Central Dispatch, one of the most exciting new features in 10.6.
  • Jesper lists some hidden gems in Snow Leopard.
1 Comment

Voices That Matter: iPhone Developers Conference


I’ve recently been invited to the 2009 Voices That Matter: iPhone Developers Conference, taking place in October in Boston, MA.

This conference is designed for Mac developers looking for a succinct, easy way to get up to speed on the specific skills needed to build, test and distribute successful applications for the iPhone and iPod touch. Erica Sadun, author of The iPhone Developer’s Cookbook and our event’s technical chair, will lead an epic group of speakers at the conference including Aaron Hillegass, Andy Ihnatko, Jon Rentzsch, Steve Kochan, Fraser Speirs, Lee Barney and lots of others.

Having missed out on yet another year of WWDC, I’m excited about this conference. Many of the presenters are developers I know well through Twitter and blogs, and I have a great amount of respect for their work. I’m pretty confident I’ll pick up plenty of great tips that will help in the iPhone development work I’ve been doing lately.

The event organizers sent me a $100 discount to post here for readers. If you’re planning on attending, register here and be sure to use the priority code PHBLOG. There’s an additional $200 early bird discount available before September 12th. Also, send me an email beforehand if you’re coming and I’ll try to say hello!

No Comments