Vincent Gable’s Blog

August 15, 2010

My UIViewController Template

Filed under: iPhone,Objective-C,Programming,Sample Code | , , ,
― Vincent Gable on August 15, 2010

I haven’t formalized this as a proper Xcode template, but this is what’s in my PrototypeViewController.m file that I copy/paste over the UIViewController subclasses Xcode makes.

@interface MyViewController ()

@implementation MyViewController
- (void) releaseViewObjects;
	if([[self superclass] instancesRespondToSelector:@selector(releaseViewObjects)])
		[(id)super releaseViewObjects];

- (void)viewDidUnload;
    [super viewDidUnload];
    [self releaseViewObjects];

- (void)dealloc;
    [self releaseViewObjects];
    [super dealloc];


Here are the reasons why, in no particular order:

Commented-Out Code is Evil

Littering source code with “comments” full of crufty, obsolete, or unimplemented code is not a good thing. Xcode’s default template is full of commented-out code. If you’re totally new to the platform, starting from the templates aren’t a bad way to learn. But in my experiance, they do harm to a production code-base, by injecting hundreds of lines of commented-out code into a project.

Share code between viewDidUnload and dealloc With releaseViewObjects

In my world, releaseViewObjects is solely responsible for cleaning up every IBOutlet, and any objects created in viewDidLoad.

There are technical reasons why this is a little scary. Calling a method in dealloc is potentially risky, because the object may be in an invalid half-torn-down state, and because Dark Runtime Magicks could be afoot (see Using Accessors in Init and Dealloc.)

But in my experience, such bugs, although as scary as they sound, are rare corner-cases and still quite fixable. But every UIViewController needs to clean up after itself, so simplifying the universally common case is a net win.

The if([[self superclass] instancesRespondToSelector:@selector(releaseViewObjects)]) test wouldn’t be necessary if I added another class between UIViewController and my real code, so that I was sure my class’ super implemented releaseViewObjects. But adding a subclass just to implement one empty method, to avoid a two-line test, isn’t worth it.

The (id)super cast is intentional, to prevent compiler warnings.

I have to use the more complex [[self superclass] instancesRespondToSelector: test, because -[super respondsToSelector:] doesn’t work.

I Won’t Really Get To didReceiveMemoryWarning

I’m not proud to admit this, but it’s true. We’ve all been told that a good iPhone program must release resources when it gets a memory warning, or else it will be killed. But in practice, there have always been better places to spend my time (or at least it sure feels that way!) Spending a few hours in Instruments to fix leaks prevents memory warnings in the first place, and that’s a bigger win.

Besides, 80% of what didReceiveMemoryWarning would do is handled in releaseViewObjects, which is automatically called by the default implementation.

So I break with Xcode and leave didReceiveMemoryWarning out of my template, because the default class won’t use it.

What About init?

I don’t have a default init(With…) method. I try to use autorelease-ed objects everywhere I can, so I’m more comfortable implementing +[MyViewController viewControllerForFoo:].

But I don’t have a default constructor of any kind, because a constructor should take every value it needs, and I don’t know what these values are until I’ve written a bit more of the class. It’s a chicken and egg problem.

Once I’ve written out a bit more of the class, I’ll usually build something that looks like:

+ (RouteMapViewController*) routeMapViewControllerWithWaypoints:(NSArray*)waypoints mapRegion:(MKCoordinateRegion)region;
	RouteMapViewController *vc = [[[self class] new] autorelease];
	vc.title = NSLocalizedString(@"The Path",@"");
	vc.hidesBottomBarWhenPushed = YES;
	vc.waypoints = waypoints;
	vc.mapRegion = region;
	return vc;

For what it’s worth I use this pattern to implement a 0-argument -init.

Empty Class Extension

Class extensions are the best way to have “private” things in Objective-C. They let the compiler catch objects using another object’s private methods. They let a class have publicly readonly, but internally readwrite, properties.

Bottom line: every nontrivial object I’ve written uses them, so they’re in my template.

Nothing Else (For Now)

My template is smaller than Xcode’s. That is by design. Outside of esoteric contests, having less code to maintain is a good thing. So I prefer a template that tries very hard to avoid adding code I don’t need.

Do you disagree with any of my choices? Please leave a comment explaining why.

July 19, 2010

#define String

When I need a string-constant, I #define it, instead of doing the “right” thing and using an extern const NSString * variable.

UPDATE 2010-07-20

Thanks to Elfred Pagen for pointing out that you should always put () around your macros. Wrong: #define A_STRING @"hello"

instead use (), even when you don’t think you have to:

#define A_STRING (@"hello")

This prevents accidental string concatenation. In C, string-literals separated only by whitespace are implicitly concatenated. It’s the same with Objective-C string literals. This feature lets you break long strings up into several lines, so NSString *x = @"A long string!" can be rewritten:

NSString *x =
	@"A long"
	@" string!";

Unfortunately, this seldom-used feature can backfire in unexpected ways. Consider making an array of two strings:

#define X @"ex"
#define P @"plain"
a = [NSArray arrayWithObjects:X

That looks right, but I forgot a “,” after X, so after string-concatenation, a is ['explain'], not ['ex','plain'].

Moral of the story: you can never have too many ()’s in macros.

And, now, back to why I use #define

It’s less code

Using an extern variable means declaring it in a header, and defining it in some implementation file. But a macro is just one line in a header.

It’s faster to lookup

Because there’s only the definition of a macro, Open Quickly/command-double-clicking a macro always jumps to the definition, so you can see what it’s value is in one step. Generally Xcode jumps to a symbol’s declaration first, and then it’s definition, making it slower to lookup the value of a const symbol.

It’s still type safe

An @"NSString literal" has type information, so mistakes like,

#define X (@"immutable string")
NSMutableString *y = X;
[y appendString:@"z"];

still generate warnings.

It lets the compiler check format-strings

Xcode can catch errors like “[NSString stringWithFormat:@"reading garbage since there's no argument: %s"]“, if you let it. Unfortunately, the Objective-C compiler isn’t smart enough to check [NSString stringWithFormat:externConstString,x,y,z]; because it doesn’t know what an extern variable contains until link-time. But preprocessor macros are evaluated early enough in the build process that that the compiler can check their values.

It can’t be changed at runtime

It’s possible to change the value of const variables through pointers, like so:

const NSString* const s = @"initial";
NSString **hack = &s;
*hack = @"changed!";
NSLog(s);//prints "changed!"

Yes this is pathological code, but I’ve seen it happen (I’m looking at you AddressBook.framework!)

Of course, you can re-#define a preprocessor-symbol, so macros aren’t a panacea for pathological constant-changing code. (Nothing is!) But they push the pathology into compile time, and common wisdom is that it’s easier to debug compile-time problems, so that’s a Good Thing. You may disagree there, and you may be right! All I can say for sure is that in my experience, I’ve had bugs from const values changing at runtime, but no bugs from re-#define-ed constants (yet).


Preprocessor macros are damnably dangerous in C. Generally you should avoid them. But for NSString* constants in applications, I think they’re easier, and arguably less error prone. So go ahead and #define YOUR_STRING_CONSTANTS (@"like this").

June 2, 2010

NSHomeDirectory() is a Bad Thing

Filed under: Announcement,Cocoa,iPhone,MacOSX,Objective-C,Programming | , ,
― Vincent Gable on June 2, 2010

Code that uses NSHomeDirectory() is probably doing The Wrong Thing. It’s not appropriate to clutter up the user’s home directory — internal application-data should be stored in the Application Support directory (or a temporary file if it’s transient). So I can’t think of a good reason to get the path to the user’s home directory. Every use of NSHomeDirectory() I’ve seen is spamming the home directory, or getting a subdirectory in a brittle way.

For sample code that gets a directory robustly, using NSSearchPathForDirectoriesInDomains(), see Finding or creating the application support directory.

Because NSHomeDirectory() encourages so many bad practices, it should be deprecated.

Disabling NSHomeDirectory() in Your Projects

Add the following macro to your prefix file:

#define NSHomeDirectory() NSHomeDirectory_IS_DISCOURAGED_USE_NSSearchPathForDirectoriesInDomains_TO_GET_A_SUBDIRECTORY_OF_HOME

Then any use of NSHomeDirectory() will give the compiler error:

‘NSHomeDirectory_IS_DISCOURAGED_USE_NSSearchPathForDirectoriesInDomains_TO_GET_A_SUBDIRECTORY_OF_HOME’ undeclared (first use in this function)

Tell Me I’m Wrong

If you’ve seen a legitimate use of NSHomeDirectory() please leave a comment! Just because I can’t think of one doesn’t mean they don’t exist.

May 26, 2010

drain an NSAutoReleasePool Don’t release it

To clean up an NSAutoreleasePool, do [pool drain]; not [pool release];

In a garbage-collected environment, sending any object a release message is hardcoded by the runtime to do nothing (very quickly). So [pool release] won’t do anything. But [pool drain] will signal the garbage collector to cleanup, and works correctly (just like release) in a non-garbage-collected environment.

Why This Still Matters on an iPhone

The iPhone doesn’t have garbage collection today. That doesn’t mean it never will. RIM and Android both support some kind of garbage collection. I’m too grizzled an Apple developer to not future proof my code, because I’ve been effected by Apple making some major runtime changes (eg. switching between PowerPC, x86, x86_64, and ARM processors). Section 3.3.1 of the iPhone SDK agreement means Apple’s runtime is the only game in town. It pays to be sure your code always plays nicely with it.

Using drain also helps your code will play nice with Mac OS X. That gives you more options to re-use and monazite it. If you decide to go the open-route, it means more people will be able to use your code.

May 25, 2010

Write dealloc FIRST

Filed under: Bug Bite,Cocoa,Objective-C,Programming | , , ,
― Vincent Gable on May 25, 2010

As soon as you give a class a new instance variable (ivar), update the class’s dealloc method (and viewDidUnload, if the ivar is an IBOutlet) to clean up the ivar. Do this before you write the code using the new ivar. Here’s why:

Never Forget

You can’t forget to release an ivar, if the code that reaps it is in place before the code that creates it. Updating dealloc first means less memory leaks.

Even with an impossibly good testing protocol, that catches every memory leak, it’s faster to fix memory leaks before they happen than to track them down after the fact.

You Know More Than They Do

Sometimes there’s an important step that must be done when cleaning up an ivar. Maybe you need to set it’s delegate to nil, or unregister for a notification, or break a retain cycle. You know this when you setup the ivar. But your coworkers don’t know this a priori. When you checkin code that leaks or triggers an analyzer warning, they’ll want to fix it, and since they know less than you do about your code, they’re more likely to miss a crucial step. (Even if you work alone, remember Future You! In N weeks, Future You will have to deal with all the code Present You wrote today … and they’ll be in the same situation as any other co-worker, because they won’t remember everything Present You knows. )

May 19, 2010


Filed under: Cocoa,iPhone,MacOSX,Objective-C,Programming,Tips | , , ,
― Vincent Gable on May 19, 2010

How to remember Cocoa memory management:

Think NARC: “New Alloc Retain Copy”. If you are not doing any of those things, you don’t need to release.

–Andiih on Stack Overflow

Personally, I like to immediately autorelease anything I NARC-ed, on the same line. For example:

Foo* pityTheFoo = [[[Foo alloc] init] autorelease];

Admittedly, this makes for some ugly, bracey, lines. But I think it’s worth it, because you never having to worry about calling release if you also…

Use a @property (or Setter) Instead of retain

In other words I would write an init method that looked like:

- (id) init
	self = [super init];
	if (self) {
		_ivar = [[Foo alloc] init];
	return self;


- (id) init
	self = [super init];
	if (self) {
		self._ivar = [[[Foo alloc] init] autorelease];
	return self;

(Or [self setIvar:[[[Foo alloc] init] autorelease]]; if you are one of those folks who hate the dot-syntax.)

It’s debatable if using acessors in init and dealloc is a good idea. I even left a comment on that post arguing against it. But since then I’ve done a lot of reflection, and in my experience using a @property instead of an explicit release/= nil solves more problems then it causes. So I think it’s the best practice.

Even if you disagree with me on that point, if the only places you explicitly NARC objects are init, dealloc, and setX: methods then I think you’re doing the right thing.


The last piece of the memory-management puzzle are retain cycles. By far the best advice I’ve seen on them is Mike Ash’s article. Read it.

May 17, 2010

Don’t Check For nil in Your dealloc Methods

Filed under: Cocoa,Programming | , ,
― Vincent Gable on May 17, 2010

There’s no need to check if a variable is nil before release-ing it, because calling a method on a NULL variable is a no-op in Objective-C. And the runtime already has a super-fast check for this case.  So adding an extra if test into your code will probably slow things down.

Doing a pointless “ ==?nil”  test is bad for two reasons.

Firstly, it’s more code for no good reason. Even if it’s just one more line, It’s one more line to debug and test. It’s one more place where something could go wrong.

Secondly, it’s not idiomatic Cocoa-code, so it signals that something strange is going on. That’s a problem for whoever is reading the code, because they have to stop and look around more carefully to figure out why the pointless tests are happening.

In summary, do NOT do this:

- (void)dealloc;


if(baseImage) {

[baseImage release];

baseImage = nil;


[super dealloc];


Do this:

- (void)dealloc;


[baseImage release];

baseImage = nil;

[super dealloc];


April 22, 2009

-[NSURL isEqual:] Gotcha

Filed under: Bug Bite,Cocoa,iPhone,MacOSX,Programming,Sample Code | , , , , , ,
― Vincent Gable on April 22, 2009

BREAKING UPDATE: Actually comparing the -absoluteURL or -absoluteString of two NSURLs that represent a file is not good enough. One may start file:///, and the other file://localhost/, and they will not be isEqual:! A work around is to compare the path of each NSURL. I’m still looking into the issue, but for now I am using the following method to compare NSURLs.

@implementation NSURL (IsEqualTesting)
- (BOOL) isEqualToURL:(NSURL*)otherURL;
	return [[self absoluteURL] isEqual:[otherURL absoluteURL]] || 
	[self isFileURL] && [otherURL isFileURL] &&
	([[self path] isEqual:[otherURL path]]);

[a isEqual:b] may report NO for two NSURLs that both resolve to the same resource (website, file, whatever). So compare NSURLs like [[a absoluteString] isEqual:[b absoluteString]]. It’s important to be aware of this gotcha, because URLs are Apple’s preferred way to represent file paths, and APIs are starting to require them. Equality tests that worked for NSString file-paths may fail with NSURL file-paths.

The official documentation says

two NSURLs are considered equal if they both have the same base baseURL and relativeString.


An NSURL object is composed of two parts—a potentially nil base URL and a string that is resolved relative to the base URL. An NSURL object whose string is fully resolved without a base is considered absolute; all others are considered relative.

In other words, two NSURL objects can resolve to the same absolute URL, but have a different base URL, and be considered !isEqual:.

An example should make this all clear,

NSURL *VGableDotCom = [NSURL URLWithString:@""];
NSURL *a = [[NSURL alloc] initWithString:@"blog" relativeToURL:VGableDotCom];
NSURL *b = [[NSURL alloc] initWithString:@"" relativeToURL:nil];
LOG_INT([a isEqual:b]);
LOG_INT([[a absoluteURL] isEqual:[b absoluteURL]]);
LOG_ID([a absoluteURL]);
LOG_ID([b absoluteURL]);

[a isEqual:b] = 0
[[a absoluteURL] isEqual:[b absoluteURL]] = 1
[a absoluteURL] =
[b absoluteURL] =

Remember that collections use isEqual: to determine equality, so you may have to convert an NSURL to an absoluteURL to get the behavior you expect, especially with NSSet and NSDictionary.

March 31, 2009

How To Write Cocoa Object Getters

Setters are more straightforward than getters, because you don’t need to worry about memory management.

The best practice is to let the compiler write getters for you, by using Declared Properties.

But when I have to implement a getter manually, I prefer the (to my knowledge) safest pattern,

- (TypeOfX*) x;
  return [[x retain] autorelease];

Note that by convention in Objective-C, a getter for the variable jabberwocky is simply called jabberwocky, not getJabberwocky.

Why retain Then autorelease

Basically return [[x retain] autorelease]; guarantees that what the getter returns will be valid for as long as any local objects in the code that called the the getter.


NSString* oldName = [person name];
[person setName:@"Alice"];
NSLog(@"%@ has changed their name to Alice", oldName);

If -setName: immediately releasees the value that -name returned, oldName will be invalid when it’s used in NSLog. But if the implementation of [x name] used retain/autorelease, then oldName would still be valid, because it would not be destroyed until the autorelease pool around the NSLog was drained.

Also, autorelease pools are per thread; different threads have different autorelease pools that are drained at different times. retain/autorelease makes sure the object is on the calling thread’s pool.

If this cursory explanation isn’t enough, read Seth Willitis’ detailed explanation of retain/autorelease. I’m not going to explain it further here, because he’s done such a through job of it.


return [[x retain] autorelease]; is more complicated, and harder to understand then a simple return x;. But sometimes that ugliness is necessary, and the best place to hide it is in a one-line getter method. It’s self documenting. And once you understand Cocoa memory management, it’s entirely clear what the method does. For me, the tiny readability cost is worth the safety guarantee.


return [[x retain] autorelease]; increases peak memory pressure, because it can defer dealloc-ing unused objects until a few autorelease pools are drained. Honestly I’ve never measured memory usage, and found this to be a significant problem. It certainly could be, especially if the thing being returned is a large picture or chunk of data. But in my experience, it’s nothing to worry about for getters that return typical objects, unless there are measurements saying otherwise.


return [[x retain] autorelease]; is obviously slower then just return x;. But I doubt that optimizing an O(1) getter is going to make a significant difference to your application’s performance — especially compared to other things you could spend that time optimizing. So until I have data telling me otherwise, I don’t worry about adding an the extra method calls.

This is a Good Rule to Break

As I mentioned before, getters don’t need to worry about memory management. It could be argued that the return [[x retain] autorelease]; pattern is a premature optimization of theoretical safety at the expense of concrete performance.

Good programmers try to avoid premature optimization; so perhaps I’m wrong to follow this “safer” pattern. But until I have data showing otherwise, I like to do the safest thing.

How do you write getters, and why?

March 29, 2009

How To Write Cocoa Object Setters

There are several ways to write setters for Objective-C/Cocoa objects that work. But here are the practices I follow; to the best of my knowledge they produce the safest code.

Principle 0: Don’t Write a Setter

When possible, it’s best to write immutable objects. Generally they are safer, and easier to optimize, especially when it comes to concurrency.

By definition immutable objects have no setters, so always ask yourself if you really need a setter, before you write one, and whenever revisiting code.

I’ve removed many of my setters by making the thing they set an argument to the class’s -initWith: constructor. For example,

CustomWidget *widget = [[CustomWidget alloc] init];
[widget setController:self];


CustomWidget *widget = [[CustomWidget alloc] initWithController:self];

This is less code, and now, widget is never in a partially-ready state with no controller.

It’s not always practical to do without setters. If an object looks like it needs a settable property, it probably does. But in my experience, questioning the assumption that a property needs to be changeable pays off consistently, if infrequently.

Principle 1: Use @synthesize

This should go without saying, but as long as I’m enumerating best-practices: if you are using Objective-C 2.0 (iPhone or Mac OS X 10.5 & up) you should use @synthesize-ed properties to implement your setters.

The obvious benefits are less code, and setters that are guaranteed to work by the compiler. A less obvious benefit is a clean, abstracted way to expose the state values of an object. Also, using properties can simplify you dealloc method.

But watch out for the a gotcha if you are using copy-assignment for an NSMutable object!

(Note: Some Cocoa programmers strongly dislike the dot-syntax that was introduced with properties and lets you say = 3; instead of [x setFoo:3];. But, you can use properties without using the dot-syntax. For the record, I think the dot syntax is an improvement. But don’t let a hatred of it it keep you from using properties.)

Principle 2: Prefer copy over retain

I covered this in detail here. In summary, use copy over retain whenever possible: copy is safer, and with most basic Foundation objects, copy is just as fast and efficient as retain.

The Preferred Pattern

When properties are unavailable, this is my “go-to” pattern:

- (void) setX:(TypeOfX*)newX;
  [memberVariableThatHoldsX autorelease];
  memberVariableThatHoldsX = [newX copy];

Sometimes I use use retain, or very rarely mutableCopy, instead of copy. But if autorelease won’t work, then I use a different pattern. I have a few reasons for writing setters this way.

Reason: Less Code

This pattern is only two lines of code, and has no conditionals. There is very little that can I can screw up when writing it. It always does the same thing, which simplifies debugging.

Reason: autorelease Defers Destruction

Using autorelease instead of release is just a little bit safer, because it does not immediately destroy the old value.

If the old value is immediately released in the setter then this code will sometimes crash,

NSString* oldName = [x name];
[x setName:@"Alice"];
NSLog(@"%@ has changed their name to Alice", oldName);

If -setName: immediately releasees the value that -name returned, oldName will be invalid when it’s used in NSLog.

But if If -setName: autorelease-ed the old value instead, this wouldn’t be a problem; oldName would still be valid until the current autorelease pool was drained.

Reason: Precedent

This is the pattern that google recommends.

When assigning a new object to a variable, one must first release the old object to avoid a memory leak. There are several “correct” ways to handle this. We’ve chosen the “autorelease then retain” approach because it’s less prone to error. Be aware in tight loops it can fill up the autorelease pool, and may be slightly less efficient, but we feel the tradeoffs are acceptable.

- (void)setFoo:(GMFoo *)aFoo {
  [foo_ autorelease];  // Won't dealloc if |foo_| == |aFoo|
  foo_ = [aFoo retain]; 

Backup Pattern (No autorelease)

When autorelease won’t work, my Plan-B is:

- (void) setX:(TypeOfX*)newX;
  id old = memberVariableThatHoldsX;
  memberVariableThatHoldsX = [newX copy];
  [old release];

Reason: Simple

Again, there are no conditionals in this pattern. There’s no if(oldX != newX) test for me to screw up. (Yes, I have done this. It wasn’t a hard bug to discover and fix, but it was a bug nonetheless.) When I’m debugging a problem, I know exactly what setX: did to it’s inputs, without having to know what they are.

On id old

I like naming my temporary old-value id old, because that name & type always works, and it’s short. It’s less to type, and less to think about than TypeOfX* oldX.

But I don’t think it’s necessarily the best choice for doing more to old than sending it release.

To be honest I’m still evaluating that naming practice. But so far I’ve been happy with it.

Principle 3: Only Optimize After You Measure

This is an old maxim of Computer Science, but it bears repeating.

The most common pattern for a setter feels like premature optimization:

- (void) setX:(TypeOfX*)newX;
  if(newX != memberVariableThatHoldsX){
    [memberVariableThatHoldsX release];
    memberVariableThatHoldsX = [newX copy];

Testing if(newX != memberVariableThatHoldsX) can avoid an expensive copy.

But it also slows every call to setX:. if statements are more code, that takes time to execute. When the processor guesses wrong while loading instructions after the branch, if‘s become quite expensive.

To know what way is faster, you have to measure real-world conditions. Even if a copy is very slow, the conditional approach isn’t necessarily faster, unless there is code that sets a property to it’s current value. Which is kind of silly really. How often do you write code like,

[a setX:x1];
[a setX:x1]; //just to be sure!


[a setX:[a x]];

Does that look like code you want to optimize? (Trick question! You don’t know until you test.)


I constantly break Principle 3 by declaring properties in iPhone code as nonatomic, since it’s the pattern Apple uses in their libraries. I assume Apple has good reason for it; and since I will need to write synchronization-code to safely use their libraries, I figure it’s not much more work to reuse the same code to protect access to my objects.

I can’t shake the feeling I’m wrong to do this. But it seems more wrong to not follow Apple’s example; they wrote the iPhone OS in the first place.

If you know a better best practice, say so!

There isn’t a way to write a setter that works optimally all the time, but there is a setter-pattern that works optimally more often then other patterns. With your help I can find it.

UPDATE 03-30-2009:

Wil Shiply disagrees. Essentially his argument is that setters are called a lot, so if they aren’t aggressive about freeing memory, you can have thousands of dead objects rotting in an autorelease pool. Plus, setters often do things like registering with the undo manager, and that’s expensive, so it’s a good idea to have conditional code that only does that when necessary.

My rebuttal is that you should optimize big programs by draining autorelease pools early anyway; and that mitigates the dead-object problem.

With complex setters I can see why it makes sense to check if you need to do something before doing it. I still prefer safer, unconditional, code as a simple first implementation. That’s why it’s my go-to pattern. But if most setters you write end up being more complex, it might be the wrong pattern.

Really you should read what Wil says, and decide for yourself. He’s got much more experience with Objective-C development then I do.

Older Posts »

Powered by WordPress