Vincent Gable’s Blog

August 22, 2008

Is an Application Running?

Filed under: Cocoa,MacOSX,Objective-C,Programming,Sample Code,UNIX | ,
― Vincent Gable on August 22, 2008

UPDATED 2009-01-13 to correctly detect background applications.

Pass in the bundle-identfier of an application, and this will tell you if it’s currently running or not:
- (BOOL) ThereIsARunningApplicationWithBundleID:(NSString*)bundleID; {
   ProcessSerialNumber PSN = {kNoProcess};
   while(GetNextProcess(&PSN) == noErr) {
      CFDictionaryRef info = ProcessInformationCopyDictionary(&PSN,kProcessDictionaryIncludeAllInformationMask);
      if(info) {
         NSString *theirBundleID = (NSString*)CFDictionaryGetValue(info, kIOBundleIdentifierKey);
         BOOL bundleIDMatches = [bundleID isEqualTo:(NSString*)theirBundleID];
         CFRelease(info);
         if(bundleIDMatches)
            return YES;
      }
   }
   return NO;
}

(It’s a good idea to test if an application is running before sending it an AppleEvent, because that will launch it.)

Interestingly, none of the the Process Manager APIs can see into another user’s process-space; but ps can; at least on OS X 10.5 and 10.4.

August 20, 2008

Hardwired Strings

With every programming language/development environment I know of, you have to do extra work to make a string localizable. For example,
errorMessage = NSLocalizedString(@"This is hard!",@"");
not simply,
errorMessage = @"This is hard!";

And it’s not just extra work, it’s a ridiculous amount of work. E.g. to create an Objective-C string, you just put an @ in front of a standard C string. But to create a localized string, you have to surround your string in ()‘s, and prefix it with a seventeen character mixed-case function-name, and finally add an empty “note” for the translator. (Rarely, you may want to add a note for the translator, and it’s good that you can, but you should not be forced to write something when it is not necessary.)

There isn’t really an excuse for this; it’s just how languages have lazily evolved.

Non-localizable (“hardcoded”) strings are a huge issue, even though they are trivially simple for programmers to fix. The problem is that translators do not work with source code, they work with resource files. So when they find a “hardwired” string that must be changed in code, they tell a programmer to fix it. And that communication is slow and costly. Especially when you consider that good localizers are probably native to the place they are localizing for — meaning that having a real-time conversation involves at least one party staying up past 3AM.

I dream of a day where "this would be localized by default"; "and"("syntactic sugar for adding optional translator notes would be there too"); and creating C"literal C-strings" would be easy.

“Unicode support libraries” are doomed to institutionalized-failure, because they will never make it easier to do the right thing. It must be so easy to create a localizable program that you wouldn’t dream of doing anything else.

Localizing In Xcode

Let me say this again in slow motion: NEVER type in ANY English string without typing NSLocalizedString() around it! This will save you SO MUCH HASSLE later on when your app is popular. Remember that enterprising polyglots can localize your code from just the binary you ship if you follow a few rules of localization, so you may wake up one day and find that someone from across the world has mailed you a your app in another language. It’s a fuzzy feeling and it gets you instant market-share.

Wil Shipley

August 5, 2008

Simplified Logging

Filed under: Cocoa,MacOSX,Objective-C,Programming,Sample Code,Tips,Usability | , ,
― Vincent Gable on August 5, 2008

I have noticed a pattern in my Cocoa code, which I have been able to simplify. I often print out the value of a variable for debugging. 99 times out of 100, the code looks like this: NSLog(@"actionURL = %@", actionURL);, where actionURL is some variable.

But using the macros, I can say LOG_ID(actionURL);. This is shorter, and non-repetitive.

The macros I use to simplify debugging (2008-09-16):

#define FourCharCode2NSString(err) NSFileTypeForHFSTypeCode(err)

#define LOG_4CC(x) NSLog(@"%s = %@", # x, FourCharCode2NSString(x))
#define LOG_FUNCTION() NSLog(@"%s", __FUNCTION__)
#define LOG_ID(o) NSLog(@"%s = %@", # o, o)
#define LOG_INT(i) NSLog(@"%s = %d", # i, i)
#define LOG_INT64(ll) NSLog(@"%s = %lld", # ll, ll)
#define LOG_FLOAT(f) NSLog(@"%s = %f", # f, f)
#define LOG_LONG_FLOAT(f) NSLog(@"%s = %Lf", # f, f)
#define LOG_OBJECT(o) LOG_ID(o)
#define LOG_POINT(p) NSLog(@"%s = %@", # p, NSStringFromPoint(p))
#define LOG_RECT(r) NSLog(@"%s = %@", # r, NSStringFromRect(r))
#define LOG_SIZE(s) NSLog(@"%s = %@", # s, NSStringFromSize(s))

Look in assert.h for insight on how to roll your own debugging macros.

August 3, 2008

How to Implement Automatic Updating

Filed under: Cocoa,Design,MacOSX,Objective-C,Programming,Sample Code,Usability
― Vincent Gable on August 3, 2008

If you are about to add automatic updating to your application (and you should), then check out the Sparkle Framework before you start. I wish I had done this before I spent a lot of time writing my own automatic updating code.

A quick-and-dirty hack.

Get your application’s version number by:
[[[NSBundle mainBundle] infoDictionary] valueForKey:@"CFBundleVersion"];
(This articles explains setting up Xcode to bake the current subversion-number into every build.)

Get the the latest version number out of a text-file on a website:
[NSString stringWithContentsOfURL:[NSURL URLWithString:@"www.your-url-here.com/whaterver/version.txt" encoding:NSASCIIStringEncoding error:nil]];
If there is any trouble, it will return nil. CAUTION: This will block the main thread for up to 30 seconds, while -stringWithContentsOfURL: tries to access the URL.

Making it Usable

If you don’t want your program to be unresponsive while it tries to get something off the internet, try this:

- (void) updatesReady
{
   //do something....
}

- (void) synchronousCheck
{
   NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

   NSURL* latestURL = [NSURL URLWithString:@"http://www.your-url-here.com/currentversion.txt"];
   NSString* latestVersion = [NSString stringWithContentsOfURL:latestURL encoding:NSASCIIStringEncoding error:nil];
   //latestVersion will be nil if there trouble was accessing latestURL.

   NSString* ourVersion = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"CFBundleVersion"];
   if([ourVersion isLessThan: latestVersion])
      [self performSelectorOnMainThread:@selector(updatesReady) withObject:nil waitUntilDone:YES];

   [pool drain];
}

//will call updatesReady iff a new version is ready, otherwise does nothing.
- (void) checkForUpdates
{
   [NSThread detachNewThreadSelector:@selector(synchronousCheck) toTarget:self withObject:nil];
}

A few thoughts on automatic updating:

When the user explicitly runs an update-check, they should get immediate feedback that something happened. You should put up a window with a spinner. Even though checking for updates may only take 100msec in your lab, if the user is on a flakey wireless connection while traveling, it could take several seconds for them.

It feels like it takes several years for an HTTP fetch to time out, if you can’t do anything while you wait.

Anything having to do with threads is harder then it looks.

“Check for updates {daily, weekly, monthly}” is a useless preference. Just because Apple’s Software Update has it does not mean you should offer those choices! They do not give the user any real control over when and how they are annoyed by requests to update. Users don’t care when the update checks are performed — they only care when new software is announced to them. Ether go with the a simple check-box that toggles automatic updating, or go with something like:
“Let me know about new software: at 12 PM”.

Display the date of the last successful update check, never display “Last Update Monday 9AM — update failed”. (This should be obvious, but I see it all the time). Version checking should be silent and unobtrusive. Don’t tell the user about it — only tell them about results.

Automatically downloading updates in the background is a great idea if they are small, and the computer has a reasonably fast internet connection.

You might also want to check out: NiftyFeatures 0.4 By Uli Kusterer .

An example project containing two classes, UKUpdateChecker and UKFeedbackProvider that can be plugged into your applications to add “Check for Update…” and “Send Feedback…” menu items to your applications.

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!

July 7, 2008

Programatically Excluding Things from Time Machine Backups

Filed under: Cocoa,MacOSX,Objective-C,Programming,UNIX | , ,
― Vincent Gable on July 7, 2008

To exclude files/folders from a Time Machine backup, you can use the C-function CSBackupSetItemExcluded().

As far as I know there isn’t an official way to do this from the command-line or a shell script. As near as I can tell, the safest way to it without using compiled C-code is:

sudo defaults write /Library/Preferences/com.apple.TimeMachine \
SkipPaths -array-add "PATH-ONE" "PATH-TWO"

where "PATH-ONE" "PATH-TWO" are of course paths to items you want to exclude.

Credit to Ellis Jordan Bojar for this solution. (original article) Using defaults instead of tinkering with .plist files directly is really the way to go!

July 5, 2008

FourCharCode2NSString

Filed under: MacOSX,Objective-C,Programming,Sample Code,Usability | , , ,
― Vincent Gable on July 5, 2008

As I have written before, the best way to convert a FourCharCode to an NSString* for NSLog()ing is to use the NSFileTypeForHFSTypeCode() function. But for the life of me I can’t remember that name, even though I use it about once a month. It’s too long, and it has too little to do with what I’m using it for.

So I have added the line:
#define FourCharCode2NSString(err) NSFileTypeForHFSTypeCode(err)
To my prefix-files, because I can remember FourCharCode2NSString().

UPDATE: (2008-08-06) There is an even easier way.

-dealloc Warning

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

The only time you should call ever call -dealloc in Objective-C is on the last line of your own -dealloc method. This call should be [super dealloc];. The proper way to dispose of an object is to send it a -release message — -dealloc will then be called if appropriate.

Now when I was first learning Cocoa, I sometimes disposed of objects by calling -dealloc directly. This caused all sorts of problems. Truth be known, if I’ve been messing with several object’s -dealloc methods, I’ll sometimes dyslex out and type dealloc when I mean release, just because it’s more fresh in my head. This is very rare, but it has happened once, and will happen again. I’m fallible like that. Murphy’s law tells us that I won’t catch it every time.

So I humbly propose that GCC should warn you if you use -dealloc any way other then calling [super dealloc]; on the last line of your own -dealloc methods.

Missing Frameworks

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

I tried using an AMWorkflowView in a project, but when I ran it, I would crash with the following printed to the console:


*** Terminating app due to uncaught exception ‘NSInvalidUnarchiveOperationException’, reason: ‘*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (AMWorkflowView)’

It turns out I just forgot to include Automator.framework in my project!

It turns out that you also have to include Automator.framework to use any OSAScriptView objects.

I hope this helps someone who googles the error message :-).

« Newer PostsOlder Posts »

Powered by WordPress