Vincent Gable’s Blog

December 8, 2008

C Comment Trivia

Filed under: Bug Bite,C++,Objective-C,Programming | , ,
― Vincent Gable on December 8, 2008

//I'll bet \
you \
didn't \
know \
you \
could \
comment \
like \
this \
in \
C/C++/Objective-C

Well, you can. Finding out was a lot of fun, believe me.

At some point, I’m not sure when, I unknowingly put a ‘\’ at the end of a block of // comments. That commented out the method-call the block was referring to. As you might guess from the fact that it had a big comment talking about why it was there, this was an important method call. I spent more time then I want to admit debugging and staring at my code trying to see the problem. Finally I noticed “hey, the color of that code is like a comment, even though it’s not in a comment”.

The More You Know!

December 4, 2008

NSAssert Considered Harmful

Filed under: Bug Bite,Cocoa,MacOSX,Objective-C,Programming,Tips | , , , ,
― Vincent Gable on December 4, 2008

The NSAssert() function is unreliable, and therefore dangerous. Plain-old assert() is a better choice.

Note that #define NDEBUG disables assert(); and #define NS_BLOCK_ASSERTIONS disables NSAssert(). One kind of assert being disabled does not mean the other kind is. Nether kind of assertion is disabled by default when building in “Release” mode — you must be sure to disable them yourself. Be careful, a user will not appreciate the difference between a bug and a failed assertion — both are a crash.

assert() immediately stops your program with a SIGABORT signal. You can’t miss a failed assert(), its behavior is predictable, and it fails fast (link is a PDF).

But a failed NSAssert() behaves unpredictably. Sometimes it stops program execution, sometimes it does not and leaves the program in a strange inconsistent state. I have entirely missed NSAssert()s failing, because I did not look at the console. if(!expr) NSLog(); would have been a better choice in the those cases, because at least I would have known how it behaved.

According to Apple,

Assertion macros, such as NSAssert and NSCAssert … pass a string to an NSAssertionHandler object describing the failure. Each thread has its own NSAssertionHandler object. When invoked, an assertion handler prints an error message that includes the method and class (or function) containing the assertion and raises an NSInternalInconsistencyException.

Complicated! The complexity means it is possible to customize what happens when an NSAssert() fails. That sounds cool, but I’ve never heard of someone needing to actually do that.

If a framework catches NSInternalInconsistencyExceptions, then your program will keep right on running after a failed NSAssert(). I have had this happen to me several times. I apologize for not having taken the time to investigate what frameworks were catching what.

Apple could change what catches what with any software update.

Variability and complexity are the last things you want while debugging. There’s no reason to invite it them by using NSAssert() over assert(). Since NSAssert() is not guaranteed to stop your program, it can not be relied on to guard against data corruption, or anything worse then a predictable crash.

UPDATE 2009-06-01: You can annotate assert(), so it prints an explanation like NSAssert(), by &&ing in a string after the condition. For example assert(i < j) is a lot more useful with an explanation: assert(i < j && "unexpected cycle in graph") — on failure it prints

Assertion failed: (i < j && “unexpected cycle in graph”), function WillHalt(), file /path/to/code.m, line 30.

November 14, 2008

Prefer copy Over retain

Filed under: Bug Bite,Cocoa,Objective-C,Programming | , ,
― Vincent Gable on November 14, 2008

(Almost) every time you use retain in Objective-C/Cocoa, you really should be using copy. Using retain can introduce some subtle bugs, and copy is faster then you think…

A Bug Waiting To Bite

The problem with using retain to “take ownership” of an object is that someone else has a pointer to the same object, and if they change it, you will be affected.

For example, let’s say you have a Person class with a straightforward setter method:
- (void) setThingsToCallTheBossToHisFace:(NSArray*)newNames {
   [thingsToCallTheBossToHisFace autorelease];
   thingsToCallTheBossToHisFace = [newNames retain];
}

And you use it to initialize a few Person objects:

NSMutableArray *appropriateNames = [NSMutableArray arrayWithObject:@"Mr. Smith"];
[anIntern setThingsToCallTheBossToHisFace:appropriateNames];

//Salaried Employees can also be a bit more informal
[appropriateNames addObject:@"Joe"];
[aSalariedEmployee setThingsToCallTheBossToHisFace:appropriateNames];

//the wife can also use terms of endearment
[appropriateNames addObject:@"Honey"];
[appropriateNames addObject:@"Darling"];
[theBossesWife setThingsToCallTheBossToHisFace:appropriateNames];


The code looks good, it compiles without error, and it has a bug in it. Because setThingsToCallTheBossToHisFace: uses retain, each Person object’s thingsToCallTheBossToHisFace field is actually pointing to the exact same NSMutableArray. So adding “darling” to the list of names the wife can use also adds it to the intern’s vocabulary.

If copy was used instead, then each Person would have their own separate list of names, insulated from changes to the temporary variable appropriateNames.

A Sneaky Bug Too

This is a particularly insidious problem in Foundation/Cocoa, because mutable objects are subclasses of immutable objects. This means every NSMutableThing is also a NSThing. So even if a method is declared to take an immutable object, if someone passes in a mutable object by accident, there will be no compile-time or run-time warnings.

Unfortunately, there isn’t a good way to enforce that a method takes an object, but not a subclass. Because Foundation makes heavy use of class clusters, it’s very difficult to figure out if you have an immutable class, or it’s mutable subclass. For example, with:
NSArray *immutableArray = [NSArray array];
NSMutableArray *mutableArray = [NSMutableArray array];

[immutableArray isKindOfClass:[NSArray class]] is YES
[immutableArray isKindOfClass:[NSMutableArray class]] is YES
[mutableArray isKindOfClass:[NSArray class]] is YES
[mutableArray isKindOfClass:[NSMutableArray class]] is YES
[mutableArray isKindOfClass:[immutableArray class]] is YES
[immutableArray isKindOfClass:[mutableArray class]] is YES

Sad, but true.

copy Is Fast!

With nearly every immutable Foundation object, copy and retain are the same thing — there is absolutely no penalty for using copy over retain! The only time you would take a performance hit using copy would be if the object actually was mutable. And then you really do want to copy it, to avoid bugs!

The only exceptions I know of are: NSDate, and NSAttributedString.

But don’t just take my word for it! Here’s the snippet of code I used to test all this:

NSMutableArray *objects = [NSMutableArray array];
//add anything that can be made with alloc/init
NSArray *classNames = [NSArray arrayWithObjects:@"NSArray", @"NSColor", @"NSData", @"NSDictionary", @"NSSet", @"NSString", nil];
for(NSString *className in classNames) {
   id obj = [[NSClassFromString(className) alloc] init];
   if(obj)
      [objects addObject:obj];
   else
      NSLog(@"WARNING: Could not instatiate an object of class %@", className);
}

//manually add objects that must be created in a unique way
[objects addObject:[[NSAttributedString alloc] initWithString:@""]];
[objects addObject:[NSDate date]];
[objects addObject:[NSNumber numberWithInt:0]];
[objects addObject:[NSValue valueWithSize:NSZeroSize]];

//test if retain and copy do the same thing
for(id obj in objects)
   if(obj != [obj copy])
      NSLog(@"copy and retain are not equvalent for %@ objects", [obj className]);

Best Practices

Get in the habit of using copy, anytime you need to set or initWith something. In general, copy is safer then retain, so always prefer it.

I believe it is best to try copy first. If an object can not be copied, you will find out about it the first time your code is executed. It will be trivial to substitute retain for copy. But it is much harder, and takes much longer, to discover that you should have been using copy instead of retain.

A program must be correct before it can be made to run faster. And we have seen there is no performance penalty for copy on most common objects. So it makes sense to try copy first, and then replace it with retain if it proves to be necessary through measurement. You will be measuring before you start “optimizing”, right? (I also suspect that if taking ownership of an object is a bottle-neck, then the right optimization is not to switch to retain, but to find a way to use a mutable object, or an object pool, to avoid the “take ownership” step altogether.)

Choose copy, unless you have a measurable justification for using retain.

UPDATE 2009-11-10: Obj-C 2.0 blocks have some peculiarities,

For this reason, if you need to return a block from a function or method, you must [[block copy] autorelease] it, not simply [[block retain] autorelease] it.

October 29, 2008

Two Help Menus

Filed under: Bug Bite,Cocoa,Interface Builder,MacOSX,Objective-C,Programming | , ,
― Vincent Gable on October 29, 2008

I ran into an issue at work where sometimes an application would have two “Help” menus, on OS X 10.5 “Leopard” (but not on OS X 10.4 “Tiger”). The problem was interacting with the UI before the application had finished enough of the AppKit-initialization process.

The application had to install a component, which involved displaying authentication dialogs and such. Because the component was necessary for the application to work correctly, I thought it would be safest to do this as early as possible. But displaying a dialog in code called from awakeFromNib ended up being the cause of the double Help Menu issue.

Waiting until applicationWillFinishLaunching: or applicationDidFinishLaunching: to interact with the user fixed the problem. (In my case, it was safe to defer the installation until then.)

I am not aware of any other issues from putting up a window “too early” … however, it seems to me that doing it is asking for trouble. The AppKit/Cocoa environment obviously isn’t 100% ready at that point. Why risk running your code with half-baked libraries if you don’t have to?

Whenever possible, I will defer “first run” behavior until applicationWillFinishLaunching: or applicationDidFinishLaunching:.

October 8, 2008

Drawing the floor()

Filed under: Bug Bite,Cocoa,Design,MacOSX,Objective-C,Programming | , , , , ,
― Vincent Gable on October 8, 2008

So when drawing a custom-Cocoa-control, I had an issue where an NSImage (bitmap) and an NSBezierPath (vector-shape) didn’t move in sync with each other.

Using floor() to force all pixel-coordinate to be a whole number fixed the problem. There is probably a much better solution — after-all this was the first custom-control I have ever done in Cocoa. But when a simple solution works…

UPDATED: 2009-05-25: @cocoadevcentral tweets,

NSIntegralRect() and CGRectIntegral() take a rect and return a copy which is aligned to integer coordinates. Good to avoid blurriness.

They sound like a better solution then calling floor() on each element of an image.

October 5, 2008

Restarting Your Mac OS X Cocoa Application

Filed under: Bug Bite,Cocoa,MacOSX,Objective-C,Programming,UNIX | , ,
― Vincent Gable on October 5, 2008

Restarting your own application is a tricky thing to do, because you can’t tell yourself to start up when you aren’t running. Here is one solution, use NSTask to run a very short script that you can embed right in your Objective-C code:
kill -9 YourPID
open PathToYourApp

Something to be aware of, kill -9 will immediately terminate your application, without going through the usual applicationWillTerminate: business that happens when an application quits more gracefully.

- (void) restartOurselves
{
   //$N = argv[N]
   NSString *killArg1AndOpenArg2Script = @"kill -9 $1 \n open \"$2\"";
   
   //NSTask needs its arguments to be strings
   NSString *ourPID = [NSString stringWithFormat:@"%d",
                  [[NSProcessInfo processInfo] processIdentifier]];
   
   //this will be the path to the .app bundle,
   //not the executable inside it; exactly what `open` wants
   NSString * pathToUs = [[NSBundle mainBundle] bundlePath];
   
   NSArray *shArgs = [NSArray arrayWithObjects:@"-c", // -c tells sh to execute the next argument, passing it the remaining arguments.
                killArg1AndOpenArg2Script,
                @"", //$0 path to script (ignored)
                ourPID, //$1 in restartScript
                pathToUs, //$2 in the restartScript
                nil];
   NSTask *restartTask = [NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:shArgs];
   [restartTask waitUntilExit]; //wait for killArg1AndOpenArg2Script to finish
   NSLog(@"*** ERROR: %@ should have been terminated, but we are still running", pathToUs);
   assert(!"We should not be running!");
}

WARNING: don’t make the same mistake that I did and test restartOurselves without some kind of guard to keep your application from restarting forever. It is very difficult to kill such a beast, because whenever it starts up it takes keyboard focus away from what you are doing…. well I’m sure you get the idea.

- (BOOL) weHaveRunBefore {
   NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
   BOOL weHaveRunBefore = [prefs boolForKey:@"weHaveRunBefore"];
   [prefs setBool:YESs forKey:@"weHaveRunBefore"];
   [prefs synchronize];
   return weHaveRunBefore;
}

September 5, 2008

ASCII is Dangerous

Never use NSASCIIStringEncoding

“Foreign” characters, like the ï in “naïve”, will break your code, if you use NSASCIIStringEncoding. Such characters are more common then you might expect, even if you do not have an internationalized application. “Smart quotes”, and most well-rendered punctuation marks, are not 7-bit ASCII. For example, that last sentence can’t be encoded into ASCII, because my blog uses smart-quotes. (Seriously, [thatSentence cStringUsingEncoding:NSASCIIStringEncoding] will return nil!)

Here are some simple alternatives:

C-String Paths
Use - (const char *)fileSystemRepresentation; to get a C-string that you can pass to POSIX functions. The C-string will be freed when the NSString it came from is freed.

An Alternate Encoding
NSUTF8StringEncoding is the closest safe alternative to NSASCIIStringEncoding. ASCII characters have the same representation in UTF-8 as in ASCII. UTF-8 strings will printf correctly, but will look wrong (‘fancy’ characters will be garbage) if you use NSLog(%s).

Native Foundation (NSLog) Encoding
Generally, Foundation uses UTF-16. It is my understanding that this is what NSStrings are by default under the hood. UTF-16 strings will look right if you print them with NSLog(%s), but will not print correctly using printf. In my experience printf truncates UTF-16 strings in an unpredictable way. Do not mix UTF-16 and printf.

Convenience C-Ctrings
[someNSString UTF8String] will give you a const char * to a NULL-terminated UTF8-string. ASCII characters have the same representation in UTF-8 as in ASCII.

Take a minute to search all your projects for NSASCIIStringEncoding, and replace it with a more robust option.

It never hurts to brush up on unicode.

August 17, 2008

launchctl Gotcha

Filed under: Bug Bite,MacOSX,Programming,UNIX | , ,
― Vincent Gable on August 17, 2008

On Mac OS X 10.5, the launchd you talk to as non-root user is not the same launchd you talk to when root. So
$ launchctl list
$ sudo launchctl list
print out different lists, and the unprivileged `launchctl list` contains processes that the root-`launchctl list` does not know about. So running a launctl command as root may cause it to fail.

I have never seen another UNIX-ish tool that would fail when run as root, but succeed otherwise.

August 15, 2008

Members Are The Devil

Filed under: Bug Bite,Design,Programming
― Vincent Gable on August 15, 2008

More and more, I am of the opinion that a member-variable is a terrible thing to have in a class. Put more sanely, a class should have as few member variables as possible.

I have squashed too many bugs in the past couple of months, where two objects had their own fields that represented the same thing .. but then got out of synch. Only one object should ever store the same value.

I guess you could say this is database-normalization, applied to general programming. And I think in that space it makes more sense.

A corollary is, never cache a value that can be calculated, without a measured performance reason.

July 17, 2008

Null-Terminated Argument Lists

Filed under: Bug Bite,C++,Cocoa,Design,Objective-C,Programming,Usability | , , , , ,
― Vincent Gable on July 17, 2008

I was using +[NSDictionary dictionaryWithObjectsAndKeys:] to make a new dictionary, but one of the objects in the dictionary was the result of a call to a method that was returning nil, so the dictionary was incomplete.

This got me thinking about NULL/nil terminated argument lists. I don’t think they are a great idea (the compiler should be able to handle the list-termination for you!), but I think they are an especially bad idea in Objective-C.

The problem that it’s very common to have a nil object in Objective-C, relative to, say C++. Many Cocoa methods return nil on error. Since doing stuff with nil (generally) won’t cause an exception, these nils stick around much longer then in other languages. As you can see, nil is a pretty poor choice of a sentinel value.

It’s the 21st century! The compiler could tell an Obj-C method using a variable-argument-list how many arguments are in the list. This is trivial when all arguments are of type id. Since Obj-C methods use a radically different syntax from C functions, it shouldn’t effect existing C-code. Unfortunately, I don’t see this being added, because Objective-C is already so mature.

In the meantime. Be a little more suspicious of any objective-C methods taking a NULL-terminated list. I wish I had a perfect solution to avoid them, but I don’t! Sometimes they are the best way to do something. If you have a great work-around for constructing, say an NSDictionary with a variable number of key/values please let me know!

« Newer PostsOlder Posts »

Powered by WordPress