Vincent Gable’s Blog

February 18, 2009

Competing Software Engineering Approaches

Filed under: Cocoa,Programming,Quotes,UNIX | , , , , ,
― Vincent Gable on February 18, 2009

Tim Bray,

…Palm’s approach is
radically different from both Android’s and Apple’s. Since they’re all here
at more or less the same time, running the
same Web browser on roughly
equivalent hardware, this represents an unprecedented experiment in
competitive software-engineering approaches.

Language Framework Notes
Apple Objective-C Cocoa Old-school object-oriented language compiled to the metal; general-purpose UI
framework with roots reaching back to NeXT.
Android Java Android Java language, custom VM, built-from-scratch UI
framework aimed at small-form-factor devices, fairly abstraction-free, based
on “Actions” and “Intents”.
web OS JavaScript “Mojo” All Web technology all the time. Innovative and visually-impressive
“card”-based UI.

(I think it’s interesting to see Windows Mobile on the list:

Windows Mobile C/C++ Windows CE/.NET Micro Philosophically tries to bring Windows to the phone. When I did WinCE development it felt like doing C++ for a Windows OS from the past.

)

I see way too many other factors to attribute success/failure of the devices to the language. So I wouldn’t call this an experiment.

But it is interesting how much development for each platform diverges at a fundamental level!

Historically most operating systems —
UNIX, OS/2, Linux, Windows, Solaris, Mac (Classic and OS X) — were predominantly, written in C/C++. While each platform has it’s own frameworks, they all have strong support for C++ development. (Although Mac OS X has is slowly dropping support for it’s C/C++ “Carbon” API, and Windows wants to be moving to C# .NET)

It’s really cool to see mobile platforms doing something radically different from each other. There are good arguments for each approach — may the best one win.

January 12, 2009

Stopping an AMWorkflow Workaround

Filed under: Cocoa,MacOSX,Objective-C,Programming,Sample Code | , , ,
― Vincent Gable on January 12, 2009

-[AMWorkflowController stop:] does not stop a workflow from executing (more info). Here is a workaround that will stop all workflows your application is be running.

When you execute a worklfow using Automator.framework, the workflow is run in its own process, which insulates it from the invoking application, and vica verca 1

. At least on Leopard, the program that runs the workflow is /System/Library/CoreServices/Automator Runner.app/Contents/MacOS/Automator Runner . It has the bundle-identifier com.apple.AutomatorRunner , and it will be a sub-process of your application, since your application kicked it off.

That gives us enough information to kill just the instances of Automator Runner that are running your worklfows. This will stop workflow execution dead in it’s tracks.


- (void) killAutomatorRunnerSubprocesses; {
   ProcessSerialNumber   PSN = {kNoProcess};
   while(GetNextProcess(&PSN) == noErr) {
      NSDictionary *info = (NSDictionary*)ProcessInformationCopyDictionary(&PSN,kProcessDictionaryIncludeAllInformationMask);
      if(info) {
         NSString *theirBundleID = [info objectForKey:@"CFBundleIdentifier"];
         if([theirBundleID isEqualTo:@"com.apple.AutomatorRunner"] && [self processWasLaunchedByUs:PSN]){
            NSLog(@"Killing AutomatorRunner sub-process: PSN={high=%u low=%u}", PSN.highLongOfPSN, PSN.lowLongOfPSN);
            KillProcess(&PSN);
         }
         CFRelease((CFDictionaryRef)info);
      }
   }
}

- (BOOL) processWasLaunchedByUs:(ProcessSerialNumber)PSN; {
   ProcessInfoRec processInfo = {0};
   //we use GetProcessInformation(), and not the more modern ProcessInformationCopyDictionary()
   //because ProcessInformationCopyDictionary stores the "ParentPSN" as a 32 or 64-bit number,
   //and it is not clear to me what the endian-safe way to transform it into a ProcessSerialNumber
   //structure is, see http://lists.apple.com/archives/carbon-dev/2007/Mar/msg00283.html
   if(GetProcessInformation(&PSN,&processInfo) != noErr)
      return NO;
   Boolean   theyAreOurChild = FALSE;
   ProcessSerialNumber ourPSN = {0,kCurrentProcess};
   OSStatus err = SameProcess(&processInfo.processLauncher, &ourPSN, &theyAreOurChild);
   return !err && theyAreOurChild;
}
   

Please let me know if this works for you, of if you have a better solution.


1
Automator.app does not appear to spawn an Automator Runner when it runs a workflow. I’m not sure why. But since the stop button works in Automator.app, understanding why might lead to a better work around. Or not.

January 7, 2009

Objective-C 1.0 Style: Don’t Name Your Enumerators “enumerator”!

Disclaimer

There is a better way to iterate over collections in Objective-C 1.0. You really should use it. It’s easier to write, easier to read, less prone to bugs, faster, and makes what I’m going to rant about here a non-issue, because you won’t have any NSEnumerator variables in your code.

Badly Named Problem

The standard iteration idiom in Objective-C 1.0 is:

NSEnumerator *enumerator = [collection objectEnumerator];
id element = nil;
while( nil != (element = [enumerator nextObject]) ) {
   ;//do stuff...
}

Unfortunately, I see otherwise steller programmers name their NSEnumerator variables “enumerator”. That’s always wrong, because it does not tell you what the enumerator enumerates. We already know that enumerator enumerates things, because it’s type is NSEnumerator, unless it’s name tells us more then that it’s hardly better then no name at all.

This is an especially amateurish practice because …

Naming an Enumerator Well is Easy!

Call it, the plural of the element variable. And if that won’t work you can always fall back on calling it collectionEnumerator.

For example, to fix:

NSEnumerator *enumerator = [input objectEnumerator];
NSString *path = nil;
while (path = [enumerator nextObject])

We should name enumerator paths or inputEnumerator. You might find “paths” to be too close to “path” in which case let the “plural form” of element be everyElement, giving everyPath.

These rules can be applied without much thought, but will improve the clarity of code.

Why enumerator is Worse Than i

Firstly, the practice of naming an the index in a for-loop i is not good. You can avoid it by renaming i to thingThatIsIndexedIndex.

But at least, for(int i = 0; i < collection.size(); i++), is concise; therefore better than a equally-poorly-named NSEnumerator.

Also, there is something to be said for the idiom you can just use collection[i] over declaring an extra element variable.

The Right Choice

Everyone agrees informative names are good, yet poorly named enumerators are everywhere (just browse Apple’s sample code!) Poorly named enumerators persist because nobody really uses an enumerator per se, they are just part of an iteration idiom. (So stop declaring them and iterate smarter). When was the last time you saw code that did anything with an enumerator besides [enumerator nextObject] in a while loop?

But bad habits matter. Don’t pick up the habit of naming something poorly when it’s easy to do the right thing.

January 4, 2009

How To Beat Web Apps

Filed under: Cocoa,Design,Quotes,Usability | , , ,
― Vincent Gable on January 4, 2009

The way Apple stays ahead of the web app trend is by creating native Cocoa experiences that can’t be duplicated in web apps — both on the Mac and iPhone.

John Gruber

December 29, 2008

Thread Local Storage in Cocoa

Filed under: Cocoa,MacOSX,Objective-C,Programming,Sample Code | , ,
― Vincent Gable on December 29, 2008

[[NSThread currentThread] threadDictionary] gives you an NSMutableDictionary that you can use for thread-specific storage.

December 28, 2008

Fast Enumeration In Objective-C 1.0

Filed under: Cocoa,MacOSX,Objective-C,Programming,Sample Code | , ,
― Vincent Gable on December 28, 2008

I have used ForEach.h to do “Fast Enumeration” in Mac OS X 10.4 “Tiger”, without any problems. You must set the “C Language Dialect” in Xcode to C99 for it to work. Credit to Michael Tsai for the code, you can find other implementations of it on his website.

With ForEach.h you can do:

#import "ForEach.h"

foreach(thing, collection) {
   /*do stuff with thing*/
}

foreacht(NSString, name, allNames)
   ;//name is typed as an NSString*

With a large collection, the foreach macro should be faster then using NSEnumerator or objectAtIndex:, because it calls the nextObject function directly, without going through Objective-C’s message sending. I have not benchmarked it, because I haven’t had a reason to optimize the mechanics of my for-loops, so I don’t know by how much. But it should give you the fast in Fast Enumeration.

If you can’t use Objective-C 2.0’s Fast Enumeration (requires Leopard or, iPhone), then I highly recommend ForeEach.h.

Bug: @encode(long double)

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

UPDATE 2010-08-16: I ran a test today, on Mac OS X 10.6.4 (i386), and the issue has been resolved, @encode(long double) evaluates to "D". I’m not sure when this change happened, or what platforms it effects.

@encode(long double) returns the same string, "d", as @encode(double), at least on i386, Mac OS X 10.5.6 / 9G55. But a long double and a double are not identical:


double aDouble = M_PI;
long double aLongDouble = M_PI;
NSLog(@"sizeof(aDouble) = %d, sizeof(aLongDouble) = %d",

   sizeof(aDouble), sizeof(aLongDouble));
NSLog(@"aDouble = %f", aDouble);
NSLog(@"aLongDouble printed as a double (%%f) = %f", aLongDouble);
NSLog(@"aLongDouble printed as a long double (%%Lf) = %Lf", aLongDouble);

sizeof(aDouble) = 8, sizeof(aLongDouble) = 16
aDouble = 3.141593
aLongDouble printed as a double (%f) =
   -88796093704928900002674917893032219152220160.000000
aLongDouble printed as a long double (%Lf) = 3.141593

I haven’t tested another configuration. TYPE_LONGDOUBLE_IS_DOUBLE in ConditionalMacros.h is 1 under __ppc__, so this might not be a problem on PowerPC.

Submitted as radar://6468314.

December 26, 2008

Always Update the View From the Main Thread

Filed under: Announcement,Bug Bite,Cocoa,Interface Builder,MacOSX,Objective-C,Programming,Quotes | , ,
― Vincent Gable on December 26, 2008

I wish I’d read this years ago:

AppKit, the GUI framework, is not thread safe. In order for things to work properly, you (almost) always need to update GUI classes from the main thread

Dave Dribin (slightly edited)

I’ve run into UI + threading problem before, but I’d just never seen this limitation of AppKit spelled out.

Dave’s article explains how to call code on the main thread better then I can.

December 22, 2008

Resources in Unit Tests and Other Frameworks

Filed under: Bug Bite,Cocoa,MacOSX,Objective-C,Programming,Sample Code | , , , ,
― Vincent Gable on December 22, 2008

To load a resource inside a unit test or other bundle, do:

NSBundle *unitTestsBundle = [NSBundle bundleForClass:[self class]];
NSString *pathToResource = [unitTestsBundle pathForResource:name ofType:fileExtension];

[NSBundle mainBundle] points to the bundle for the current executable, so it’s handy in an application (where it will point to your .app bundle). But since unit tests are loaded into another program or test-harness to run, it’s not appropriate to use it in a unit test.

How To Multi

Avoid distributed computing unless your code is going to be run by a single client with a lot of available hardware. Being able to snarf up CPU cycles from idle hardware sitting around in the user’s house sounds cool but just doesn’t pay off most of the time.

Avoid GPGPU on the Mac until Snow Leopard ships unless you have a really good application for it. OpenCL will make GPGPU a lot more practical and flexible, so trying to shoehorn your computationally expensive code into GLSL or CoreImage today just doesn’t seem worth it.

Using multiple processes is a good idea if the subprograms are already written. … If you’re writing your code from scratch, I don’t recommend it unless you have another good reason to write subprocesses, as it’s difficult and the reward just isn’t there.

For multithreading, concentrate on message passing and operations. Multithreading is never easy, but these help greatly to make it simpler and less error prone.

Good OO design will also help a lot here. It’s vastly easier to multithread an app which has already been decomposed into simple objects with well-defined interfaces and loose coupling between them.

Mike Ash (emphasis mine, line-breaks added). The article has more detail and is very much worth reading.

One point that this advice really drives home for me is that you need to focus on making good code first, and defer micro-optimizations. If taking the time to clean up some code makes it easier to parallelize, then you are optimizing your code by refactoring it, even if at a micro-level you might be making some of it slower by, say, not caching something that takes O(1) time to compute.

Apple does not sell a Mac that’s not multi-core, and even the iPhone has a CPU and a GPU. There’s no question that optimization means parallelization. And all signs point to computers getting more parallel in the future. Any optimization that hurts parallelization is probably a mistake.

« Newer PostsOlder Posts »

Powered by WordPress