Silicon Valley Cocoaheads April Meeting Now Available On Video

Two videos and slides of the April Cocoaheads meeting is now available online. For details, see Scott Stevenson's blog entry. There's a total of some 750MB of material.
It featured Scott (seen above) on user interface design, and Joar (below) digging into the debugger.

I'm in the audience asking intelligent questions.
Cocoa Programming for Mac OS X Third Edition
Cocoa: How To Sync Views With A Color Preference Slider
PP has a thumbnail browser, as any photography-oriented app has, and I want to be able to control its background color. Just like Aperture I have a slider in my prefs panel that changes the gray level of the background and need to have that stored in the user's preferences. Since PP is a document-based app (I can have many document windows open at the same time), changing the browser background has to affect all the open documents and should do so in real time so the user can see the result.
Here is my prefs panel. Not much there yet:

The slider is set up to deliver a number between 0.0 and 1.0 and continuously return its state. The prefs panel XIB file also has an NSUserDefaultsController. The file's owner is a custom window controller:

I use three separate mechanisms for keeping everything in sync: actions, bindings, and notifications. Here is all of it together in one diagram:

The slider, NSUserDefaultsController and preferences file are joined together with bindings. I bind the slider's value to NSUserDefaultsController:

so that the controller is notified of all changes to the slider value. The NSUserDefaultsController keeps the prefs file on disk in sync. That is 100% of what is needed to handle the slider and the prefs. To set up the initial preferences I create the defaults in my application object:

To keep the browser background color in sync with the slider I have to be able to tell the browser's view controller that the value has changed so that it can get it from the NSUserDefaultsController object. This is a two-stage process: the slider tells its window controller via its action and the window controller tells the browser view controller through a notification:

To update the browser views, each instance of the browser view controller listens for notifications that indicate the color has changed and sends the appropriate message to its view:

The above two methods are called at appropriate times by the browser's window controller. The color is updated like this as the notification is received:

Finally, to set up the initial color the browser view controller implements this code:
That's it. Having set all of this up I can use the same mechanisms for handling other preferences and parameters that affect the browser or other views. I'm understanding the value of following the MVC pattern: it gives everything a place -- if you can figure out where that should be.
How To Report A Bug

Home For Some: 1/1000s f/4.5 ISO200 200mm, -0.3ev, Canon 30D, Canon 70-200L IS f2.8
Apple has a long and comprehensive guide for reporting bugs. It strikes me that this information should be built in to the bug reporter page. If I have a Mail bug and I state that in the drop-down menu, then the Mail-specific information should appear so I know what to provide. Similarly the template format should appear as just that: a template.
But I know exactly what to do: file a bug. See rdar://problem/5815223. (That link won't work for anyone outside Apple).
Busy

The Road Ahead: 1/400s f/4.5 ISO200 200mm -0.3ev, Canon 30D, Canon 70-200L IS f2.8
I took the photo above of a cyclist as he went past at some speed, not knowing if I actually had a photo at all. There is a neat reflection of the road ahead in the sunglasses.
Not many updates recently since there have been many things competing for my time: family, taxes, work, job hunting, and coding being the main distractions. Some photography, but not a huge amount. Aperture is fast and there is just not a lot of news about it right now, so not so much to blog about it.
I've been working as a technical writer and advisor for a chip company in Cupertino for the last month, but that's a temporary position and the hunt for a real job continues. It's an interesting contrast to my previous employer: no phone calls, no meetings, and almost no email. I can actually sit and get things done all day.
After thinking about a photo-oriented Mac OS X application for a long time, I've taken the plunge and started bashing out code. I'm learning great chunks of Cocoa as I go along, so progress is slow but rewarding. I have no idea when I will be done, or even what "done" will be right now, but my plans are to make it useful and valuable enough that photographers will buy it. It will be Leopard-only.
Aperture Export SDK: Missing Files
It failed at this line:
#import <PluginManager/PROAPIAccessing.h>in ApertureExportPlugIn.h. The PROAPIAccessing.h file is missing because it and PROPlugInBundleRegistration.h are not included in either Leopard or the ApertureSDK 1.5.5.
To fix it , I copied across the Headers folder that contains those two from a Tiger back up. The full path is /Library/Frameworks/PluginManager.framework/Versions/B/Headers. There is already a soft link for Headers that is correct. It should look like this:

Aperture: Complexity Killed Aperture 1.5
I've looked a little at the internals of Aperture 2.0 and there are some striking differences between the two. It looks as if the whole core of the application has been rewritten.
Here is one thing I found. That diagram below is the data model for Aperture 1.5. The boxes represent information stored about things like versions, albums, vaults, adjustments etc., all the things that are carefully managed by Aperture and kept in a consistent state, all the things that are needed to display and manipulate images through the interface:

What matters is the number of lines in the diagram. I reckon there are about twenty. Each one is a relationship between the data in the boxes and many lines means much complexity and lots of work to keep things in order. And the impact of complexity grows very quickly as the number of items increases.
Now have a look at the data model for Aperture 2.0:

Still plenty of boxes, several more in fact, but hardly any lines. And only two are actual relationships, the two in the center representing inheritance instead. This means that Apple has eradicated the complexity inherent in the data model and moved it elsewhere, clearly to something faster.
This is at least partly why Aperture 2.0 is so much faster than Aperture 1.5. The other benefit of removing the complexity is that reliability should increase, so I'm hoping for a more stable, less buggy application.
For anyone wondering how I got hold of the data models for Aperture; it was easy. I just decompiled the .mom file in the application with Xcode.
Random Wok On Aperture 2.0
Note that Aperture 2.0 no longer displays a sheet to show progress. Instead, it exports in the background and progress is shown in Aperture's tasks window. Look at the bottom of the window next to the tools to see what is happening in the background:
Clicking on the spinner shows more detail:

A new feature in Aperture 2.0 is the ability to pause activity. That plus background operation makes exporting so much nicer.
[Update: A couple of problems have appeared if Random Wok 1.0 is used with Aperture 2.0. See below]
If used with Aperture 2.0 the behavior with respect to clashes with existing files has changed. With Aperture 1.5 Aperture would never supply an existing file name. However with 2.0 it does not check, and so plug-in exports will overwrite existing files with the same version name. Export to empty folders to work around.
If used with Aperture 2.0 the behavior with respect to clashes with existing random files has changed. Random Wok 1.0 will issue a warning if random files are exported that have a name clash, as before. However with 2.0, Aperture does not think that the export has finished and will show the export continuing forever in the background. This is usually only an issue if Freeze is used and repeated exports to the same place are performed. Quit Aperture and relaunch to fix.
C4 Conference Video Posted

Wolf Rentzsch has posted the first video from the C4 conference that took place in Chicago last year. It's entitled Indie Ethos, and talks about the place of independent Cocoa developers in the world.
Here is the complete list. One will be posted each week.
- Wolf Rentzsch: Indie Ethos
- Wil Shipley: Monster Marketing
- Daniel Jalkut: Application Acquisition
- Shawn Morel: Virtualization Vivisection
- Bob Ippolito: Exploring Erlang
- Adam Engst: Hacking The Press
- Tim Burks: RubyObjC & Nu
- Cabel Sasser: Coda Confidential
Update: Will Shipley's talk about hype is up now.
Waffle

Waffle is a blog that covers a multitude of geeky, webby, and Appley subjects. It's technical and meaty. But somehow never waffly.
[self setNeedsDisplay:YES]; Cocoa Programmer Tee-Shirt

Stand out in the crowd with a Cocoa tee-shirt. I've a few more ideas that I will convert into products when I get a chance.
You can buy this one from Zazzle. It has white lettering with the code [self setNeedsDisplay:YES]; on the front and the back. You can pick any dark color shirt you like. I get a cut of the proceeds.
Cocoa Cheerleaders

Cocoa Cheerleaders is brought to you by the team at PyrusMalus. It's a large collection of links to blogs, articles, books, code, and other information about Cocoa.
My interest piqued by the name, I discovered that PyrusMalus is the Latin name for the Domestic Apple tree. And there is a mystery application in the works looking for alpha testers called Atlantic.
The Mac Developer Network

The Mac Developer Network is hoping to become your first port of call for all things to do with Mac development. So far it features two Cocoa-oriented podcasts (iTunes links): Late Night Cocoa and Mac Developer Roundtable, both the creation of Steve Scott.
Late Night Cocoa is one-on-one discussion with Mac developers about many Cocoa-related subjects, while Mac Developer Roundtable is a group discussion.
Leopard: NSOperation and NSOperationQueue Example
Usually it is hard to use CPU resources efficiently and reliably, but these new features of Leopard make it simple. By packaging compute-intensive operations into NSOperation objects all the complexity is handed off to the operating system.
Notable in this example is that there is no code for locking. That's all handled automatically. There is also no code to manage dependencies between parts of the expression that are being evaluated on multiple threads and potentially multiple CPUs. Dependencies are expressed in the code, but not explicitly managed.
Since this is Objective-C 2.0 you can also see @properties and @synthesize at work. And marvel at the lack of memory management.
The site also has many other goodies for people using Macs for scientific environments including a script repository, and a Core Animation tutorial.
Leopard: New Developer Features

Deric Horn gave a very informative one-hour talk at Cocoaheads at Apple in Cupertino this week covering the developer improvements in Cocoa for Leopard. There are so many improvements under the hood that it is hard to remember all of them and Deric's talk served to fill in those blanks. Attendance was very good, and there were plenty of new faces. If you live anywhere nearby it is worth a visit. We meet in Town Hall, building 4. That's the auditorium where Steve Jobs introduced the new iMac, iWork, iLife, and .Mac in August.
I recorded the audio on my Canon S3 and edited it in GarageBand. You can download the file (AAC stereo, 30MB) via the Silicon Valley Cocoaheads page.
Learn Cocoa At Stanford

Stanford University has a Cocoa programming course. Information about the course, code, and the lecture slides are available online.
Leopard: Objective-C 2.0 Part Two
It's all good stuff -- both the features in Objective-C 2.0 and Scott's presentation of the material.
Leopard: The Ars Technica Review
Cocoa: Developer Changes In Leopard
Behind the scenes views must be his forte because his about page reveals every last detail about him, down to the color of his underwear (well almost -- but it does mention socks).
NSCoder Night

Chris Hanson has announced NSCoder Night: every Tuesday 7:00pm to 9:00pm. Anyone who is interested in Cocoa/Mac programming can show up at Orchard Valley Coffee in Campbell to get help, give help, show, write, debug, whatever. Scott Stevenson has an announcement that features a Google map.
The first meeting is of course after Leopard's release, so the NDAs will no longer apply and there will be much rejoicing.
The Knowledgeable Novices Syndrome
Why is it impossible to find a tutorial on how to write a jpg or bmp etc file from an nsview? surely this is basic bread and butter programming. I have finally got through the IB barrier, I can delegate, i can use a timer, i can draw paths with mice but i cant get to write a b****@@@@ view to file! I've been googling for 4 days now, i have "programming with quartz" in front ofg me as i write, i have "cocoa programming for os x" i have "vermont recipes", i have wall to wall bookmarks to the cocoa drawing guide and yet i still cant find a single example to get me on my way!!!!!!
And everyone is telling me how wonderfully simple it all is.
AAAARRRRRRGGGGGHHHHHH!!!!!!!!!!!!
I replied thus in the answer to this conundrum:It's not as if I havn't programmed most of my life!!
I write c, perl, pascal, prolog, cobaol, algol, fortran name ive programmed it. why can't i jkjlskadjlsajdljsdlsadflkahjsjdkalj
I have a name for this: it's the knowledgeable novices syndrome.
Ignorant novices feed fine by nibbling on the tasty morsels of code that Scott and other serve up. Ignorant experts need help with the unfamiliar utensils and spices, but are otherwise great code cooks. Knowledgeable experts make entire code meals table-side from raw reference materials in real time.
I'm one of these knowledgeable novices -- not as frustrated as the quoted poster -- but still encountering the same kind of issues.Knowledgeable novices are a challenge. They just want to make and eat a sandwich, but are having the darndest time doing it. Their knowledge is actually an encumberance, since they must unlearn what they think they know about sandwiches in order to make one the Cocoa way. There is no cutting of bread and spreading of peanut butter as they are sure there must be; just lamination, repitition, and bounding polygons applied to a couple of raw materials.
Cocoaheads Meeting October

Cocoaheads this month is Thursday 11th, and the subject is Google APIs for Cocoa. Scott Stevenson has a page with more information. I'll be there.
REAL Software Is Looking For A Cocoa Programmer

Geoff Perlman at REAL Software is looking for a Cocoa programmer to help them complete their Cocoa platform layer and improve their Mac support for REALbasic. If you haven't met REALbasic yet, it's worth a look. It's a cross-platform programming system for Mac, Linux, and Windows particularly suited for rapid deployment, similar in many ways to Visual Basic.
Cocoa In Pieces


Two new sites have appeared recently: CocoaTraces and CodeBeach that fit something of the same need. They are both repositories for pieces of working Cocoa source code, stored in such a way that it should be possible to find it if you need it.
Aperture Plugin: Integrating Localized Data Part 2

Now the strings in my code and my image are localized into French as well and English, I can move on to the strings in the interface. So far the French nib is just a copy of The English nib, created when I made the French nib localization. I used nibtool to extract the strings before translation, and I use nibtool again to put the translated strings back.
To do this I fire up Terminal, cd to the French.lproj folder and use the following command line:
nibtool -w new.nib -d file.strings Random_Wok.nib
This creates a new nib file with the English strings replaced by French ones. I use the Finder to replace the old nib with the new one and I am done. Now my resources look like this:

But if I run the plug-in in French, some of the strings no longer fit:

This is unfortunately typical for English. With its huge vocabulary, English can take up as little as 50% of the space of other languages. So my nice tight interface needs adjusting.
And there is a problem with subversion. After checking all of this in I find that my repository does not contain the French files and the NoImage.tiff file is in both the localized and the main folder:

To fix this I do two subversion things: svn delete the extra TIFF and svn add the folder and its contents. Svnx could do the delete, but not the add. After a fair amount of trying things that did not consistently work, I eventually went to the command line, did a svn add of the French.lproj folder, then quit and relaunched Xcode, then finally did a commit. That worked and now everything is synchronized.
I fix the layout with IB, but don't neaten it up yet. That's because I want to run it past my translator again to make sure nothing weird has happened that I won't spot. Once the translator has OKed it, I'll peek the pixels and straighten everything.
And then there is the "Images Selected" binding. I have this set up with two display patterns, one for the number of images and one for the pluralization string. For French I have to put the second string in twice since both words gain an "s" in the plural:

When I come to add German, this will break. The German strings are "Bild ausgewählt" and "Bilder ausgewählt". There is an "er" added in the plural, not an "s". Japanese is easy: no plurals exist in the language. A better solution is to put both singular and plural strings in the strings file and do all of this in code.
The other parts of this series can be found via the Cocoa page.
Aperture Plugin: Integrating Localized Data Part 1

Now my translators have sent back localized versions of Localizable.strings, file.strings, and images that I sent to them, I can integrate them into my project. Here is how my project is organized right now:

To localize the NoImage.tiff image, I select NoImage.tiff and get Info, then click on Make File Localizable:

This changes the image into a group and shows the targets that it is associated with:

The Resources have been rearranged like this:

Clicking on the General tab shows the languages that the image is localized for:

I'm going to add French, so I click Add Localization and select French. The French image created by Xcode is just a copy of the English image at this stage:

To get my French image in, I change its name from PasDimage.tiff to NoImage.tiff so that the code will be able to access it with the same file name and replace the current image in the French.lprog folder via the Finder. Xcode has a handy contextual menu item called Reveal File In Finder to help with this.
To Localize the strings I do the same sequence, this time putting my English Localizable.strings into the English localization as well as the French Localizable.strings file into the French localization.
I localize the nib file too, creating the localization, but just leaving it as a duplicate of the English for now. I want to see how Random Wok works in French with what I have to far. Only a few things will be French at this stage: the progress message and the missing thumbnail image will show me that things are working correctly. But how to run in French?
I go to the International preference pane and move French to the top:

Now when I run Aperture it will be French.
But when I do, I find that the NoImage image is not there. And when I run it in English it is not there either. The problem is this code:

I get the TIFF file using a path that does not take into account the localization folders (English, French). So the initWithContentsOfFile method fails and returns nil. The fix is to use -pathForResource:ofType:inDirectory with a nil directory name:

And now the image shows up correctly when I run in French or English:

Next is fixing the interface strings.
The other parts of this series can be found via the Cocoa page.
A Guide To Objective-C for C++ Programmers
Aperture Plugin: Preparing For Localization

Random Wok 1.0 is currently not localized: the only language it supports is English. Before I release the 1.1 version I am going to add translations for the languages that Aperture supports: French, German, and Japanese. This requires extra files in the plugin's bundle that provide the language information.
To prepare, I replace all the messages and strings that are generated by the program and are human-readable with macros that retrieve the localized version. Code like this:

is replaced by code like this:

I use the NSLocalizedStringWithDefaultValue macro because it allows me to provide a key (exporting-images in this case) that is not the same as the string Exporting Images.... It also supports use of a specific bundle. I need that because Random Wok is a plugin and otherwise Aperture's main bundle would be used.
Once I have replaced all the strings in my code with macros, I use the terminal to run the genstrings utility on all the source files in my project:

I get this entry in the text file Localizable.strings created by genstrings for the exporting-images string above:
To provide for other languages the Localizable.strings file is duplicated and the string on the right replaced by the translation. When the plugin is run, the correct language files in the bundle are accessed and the key used in the code (exporting-images) matched with the entry in the file. Since the file is encoded UTF-16, the right hand string can contain ASCII and any unicode characters.
There are two other sources of strings that I need to worry about for localization in my plugin. First, the nib file contains all the strings used in the interface and it is currently English-only. To fix that I will need a new nib file for each language and will probably have to adjust the placement of some interface elements due to the size of the new strings. Second, I have an image that is displayed when there is no thumbnail available that says "No Image". That will have to be replaced with a new image for each language.
Apple provides a tool for helping with the translation of nibs called nibtool. Nibtool used with the -L option extracts all the strings from a nib file and sends them to stdout. The Random Wok nib file generates entries like these:

As before, a translation replaces the right hand string. Nibtool is used again to replace the strings in copies of the nib file with the translated versions.
The other parts of this series can be found via the Cocoa page.
CocoaHeads May 10: Write An Aperture Plug-In

CocoaHeads on May 10th at the Apple campus in Cupertino features John Anon giving a presentation on writing Aperture Plug-Ins. More information on Scott Stevenson's site.
Aperture Plugin: Problems With Arrays and Key Presses

A problem that I encountered along the way as I implemented my cache was that any change to the data always caused the array controller to load all the elements. This was exactly what I was trying to avoid with a cache, yet it was happening.
After much hair-pulling (and posting to Apple's Cocoa mailing list) I figured that the array controller believed that my array (implemented by methods in my Random_Wok class) was immutable, and therefore any observed change must mean that the entire array had changed and so need a reload. The fix was to make the array controller believe that the array was mutable. To do this I added three more methods:

These are the mutable array methods. I didn't even have to write any code for them because they are never called. They are just there so that the array controller knows that my array is mutable and so will allow updates to individual elements.
Another problem I found that was while the Page Up and Page Down keys worked on the NSTableView, the Home and End keys did not. A little odd. To fix this I subclassed NSTableView and overrode -keyDown:.
I created a custom class called BTKeydownTableView and told Interface Builder to use it instead of NSTableView. Here is the interface:

The implementation is very simple. I read the first character from the event queue and act on it:

To scroll the window to the right place I tell the view to scroll to the first or last rows, as required.
The other parts of this series can be found via the Cocoa page.
Aperture Plugin: Caching Table Data

Retrieving the thumbnail image and generating the text for the table is time-consuming and called very often by the array controller that is controlling the table of images. This results in very slow scrolling of my table. To solve this problem, I added caching; the idea being that repeated requests for the same data come out of memory and do so quickly.
Adding caching was relatively simple, at least to implement simply. Here is the code:

The cache needs a key to cache on. For this I turn the index number into a string and use that as the key. The cache itself is a mutable dictionary that holds dictionaries:
This stores the data I get from Aperture fine and the interface is fast again. But now I have another problem. When the random file name parameters are changed, the cached data becomes stale. So each time a change occurs, I must update the cached text:

And the cached images:

This code enumerates through the cached data replacing the cached text and thumbnail objects. Bindings take care of the table updates. -updateCachedFilenames is called whenever anything changes that could affect the file name, such as a change of alpha case:

-updateCachedImages is called when the type of image changes:

This all works well, and is how Random Wok 1.0 was released. But it still has a problem. The cache grows forever, eating memory as it goes. And as the cache grows, the time taken to update the cached data grows. What is really needed is a cache that throws away the oldest entry once it reaches a certain limit and more data is added. So that is what I implemented next.
The other parts of this series can be found via the Cocoa page.
Aperture Plugin: Improving Image Table Performance

My first attempt at providing table thumbnails was to load an NSMutableArray with all the images that the user has selected when the plugin starts. Unfortunately there can be a significant delay while they are retrieved from Aperture: above a few hundred the delay becomes irritating. Once the data was in my array, access was fast and the table scrolled up and down smoothly.
To improve start-up performance I replaced my array ivar imageTable with two methods: -countOfImageTableData and -objectInImageTableDataAtIndex:. Now, through the magic of KVC the array controller instantiated in the nib will access these two methods instead of the array. In fact it was trying to do that all along, failing, and falling back to accessing the ivar directly. The idea is that by generating the data on demand, the start-up performance problem will go away and the time taken distributed across all the images as they are viewed in the table.
Here is the code for the first method:

The check for the API version exists because my code simply does not support it. There used to be a less efficient way to retrieve thumbnails that I have no intention of coding. The result of this is that the image table is blank if an old API is detected. I also log a message to that effect on initialization, so it is not a complete mystery to the user.
The second method is very simple:

The code for -textForImageAtIndex: and -thumbnailForImageAtIndex: is not simple, however. But it is straight forward. The text code gets the properties of the image from Aperture and formats it appropriately. The thumbnail code is much easier to follow:

Master images (and potentially any image) don't have thumbnails, so I have to substitute. I do that with a small TIFF image that I put into the plugin bundle that says "No Image".
How did I do? Start-up was fast, even for thousands of images, so that problem was fixed. But there were other problems. Scrolling was dog slow. Logging showed that -countOfImageTableData and -objectInImageTableDataAtIndex: were being called for practically every pixel of scrolling I was doing, retrieving the image and generating the text each time. Horrible.
So the next step was to implement caching: retaining the images and text in memory and delivering those instead of getting them from Aperture each time they are needed.
The other parts of this series can be found via the Cocoa page.
HUDs Just Like Aperture's
Aperture Plugin: Implementing A Table Of Images

At this point in the project I decided two things: that I was going to release the plugin as 1.0 in a month, and that I needed to change the interface. I had already switched from a vertical arrangement with the prefix on top, to a horizontal arrangement with the prefix on the left. The trigger for this next change was the unsatisfactory display of the example random filename and the need to distinguish between what happens to the random naming when the freeze feature is used and is not.
The final version I decided to go with features a table that shows a thumbnail, plus the image version name, the image caption, and the new random name. This is the clearest way to show what is going to happen: show it happening.

By using the propertiesWithoutThumbnailForImageAtIndex: and thumbnailForImageAtIndex: methods I can get the data I need from Aperture for each table entry. So my plan was to bind the table to an array controller and bind the array controller to an array in the Random_Wok object that contained all the thumbnails and text. Updating the thumbnails and text would cause changes to propagate through the controller to the view as needed.
So I added an array controller to the nib and called it ImageTable:

I then bound it to the model like this:

and set up like this:

The model key is imageTableData and I use the keys thumb and text to access the data for the columns. So to support the needs of the array controller I implement an array called imageTableData as an ivar in Random_Wok and fill it with dictionaries with keys thumb and text, corresponding to NSImage and NSString objects I want to display.
I set up the table view like this:

Notice that I actually used a custom class for this. More on that later. The first (image) column is set up like this:

To display the image, I drag in an image cell. The properties of the image cell is accessed via the small triangle top right:

The inspector shows it as an NSImageCell, set up this way:

Now onto the bindings. The first column is bound to the array controller and uses the thumb key to get data from the model:

The second column is set up this way:

And bound to the text key through the array controller like this:

As I discovered while attempting to bind each table column to a separate array, setting up table column bindings also automatically sets up the the table bindings. This makes it impossible to bind separate columns to separate array objects: they have to all go to one object and then use the key path to get data from separate places. This pretty much means that you need an array of dictionaries to drive a table.
To provide data for the model, I loaded all the thumbnails and text into the array during the plugin initialization. Through the bindings I was able to change the dictionary contents and have the table update automatically. This all worked fine for a small selection of images.
However if I selected 500 images, the array would take a long time to fill. Worse, this was happening before anything was displayed (since the array controller was set to prepare content), making it look like the plugin has frozen. And changes to the text caused by changing the parameters for the random file names were also very slow because they too would be performed 500 times on all the items in the array.
So another approach was needed.
The other parts of this series can be found via the Cocoa page.
Aperture Plugin: Better Logging

The logging I have been doing is very primitive. I call NSLog() to see what I want to see and have to manually insert and remove these calls (or mess with comments) to control what is going on. It's time for something better. Looking around, I found a handy logging class at Borkware that does much of what I want called MLog.
It implements a logging system that includes the line number and source file name with each message. This is very useful for understanding what is happening when reading the logs. The change I made to that code was to add control over the logging level.
Here are the definitions for my version of MLog.h. I implement seven levels and add the ability to revert to standard NSLog() calls, or to remove all the logging code completely:

Macros take care of inserting the correct code and extracting the file name and line number from the preprocessor. The class implements two class methods: one for actually logging messages, and one for setting the current log level. The idea of the level control is that the minimum log level can be set either by an environment variable or by code and only messages logged at that level or above will be shown.
The Implementation includes a static variable that holds the current log level:

Initialization is done in the class initializer:

It reads the environment variable MLogMinLevel and uses that to set the initial level. The logging code compares the logging level passed to the method with the current level and ignores those below the minimum:

The level setter code is very simple:

To use the logging, I add lines like this to my code:

and it provides messages that look like this that include the level, the file name and the line number:
Since I provide logging control with an environment variable, I can quite easily create build configurations that behave differently. If I go to the Project menu and select Edit Project Settings I can duplicate the current Debug and Release configurations and make two new ones:

Clicking on on the Build tab lets me set these up:

I edit the preprocessor macros to include the symbols I need to control the logging system. The Release No Logging configuration sets __BTREMOVE-LOGGING, for instance. Once set up I can change the current configuration I want to build and run from the main XCode window just by selecting it:

For this to fully work I edit the custom scripts I added to copy the executable and run Aperture, since the build names have changed and there are more of them.
The other parts of this series can be found via the Cocoa page.
Aperture Plugin: Creating A Universal Binary

Random Wok is only being compiled for Intel right now. I need a universal binary so that it will run on the PowerPC architecture as well. This is easy to change. I select the Random Wok target:
Then click on the Info button, and under the Architectures tab, select what I need:

That's all there is to it. Everything happens behind the scenes.
The other parts of this series can be found via the Cocoa page.
Aperture Plugin: Automating Builds And Using The Debugger

So far in this project all my debugging has been done with NSLog() calls since the code is pretty simple. To run my plugin each time I have been dragging the binary from the Build folder to Aperture's export plugins folder, launching Aperture, and then selecting Random Wok from the File > Export menu.
So how about debugging with the debugger? If I do a debug build, go through the same steps, and the run Aperture, my breakpoints are never hit. What is going on?
This is happening because the application, Aperture, is not being run by the debugger, and so my plugin is not being run by the debugger. To make XCode run Aperture I modified the instructions I found in a technical Q & A on Apple's developer site that shows how to handle this situation with a Web Kit plugin. In my case I create a new custom executable in the Projects folder on the left side of the XCode window and set it up this way:

Then I make sure that my build options for the debug build are set correctly: no optimization, generate all symbols, don't strip:

Now I can set breakpoints and have them hit:

I still have to copy the executable and run Aperture manually. But there is a way to fix that. I add a new run script :

And set it up like this:

The debug version is set up with a symbolic link and the release version with a copy. Here is the full text:
# clean up any previous products/symbolic links in the target folder
if [ -a "${USER_LIBRARY_DIR}/Application Support/Aperture/Plug-Ins/Export/${FULL_PRODUCT_NAME}" ]; then
rm -Rf "${USER_LIBRARY_DIR}/Application Support/Aperture/Plug-Ins/Export/${FULL_PRODUCT_NAME}"
fi
# Depending on the build configuration, either copy or link to the most recent product
if [ "${CONFIGURATION}" == "Debug" ]; then
# if we're debugging, add a symbolic link to the plug-in
ln -sf "${TARGET_BUILD_DIR}/${FULL_PRODUCT_NAME}" \
"${USER_LIBRARY_DIR}/Application Support/Aperture/Plug-Ins/Export/${FULL_PRODUCT_NAME}"
elif [ "${CONFIGURATION}" == "Release" ]; then
# if we're compiling for release, just copy the plugin to the Internet Plug-ins folder
cp -Rfv "${TARGET_BUILD_DIR}/${FULL_PRODUCT_NAME}" \
"${USER_LIBRARY_DIR}/Application Support/Aperture/Plug-Ins/Export/${FULL_PRODUCT_NAME}"
fi
Here is how the debug version looks in the Export folder:

Now when I compile and run or compile and debug, the script is run and Aperture is launched. Any breakpoints I have set work.
The other parts of this series can be found via the Cocoa page.
Subversion Part 4: Creating A Release

Now I have my repository set up, my code imported, and a working copy checked out that I am doing development on, I am going to release a snapshot of the current code as a beta, since I want some people to test it. In order to be able to keep working on the main code (in trunk) while I wait for feedback from testers I have to fork my code. If the testers find a problem and I fix it, I want to send out just the fix, not the current development version with the fix. Later I can merge the fix back into my main code.
Using subversion I do this by copying my code base in the trunk releases virtual folder into a new folder. After making sure that my project is checked in, I open svnX and make sure the correct revision is selected in the top pane. By selecting trunk:

and clicking on the svn copy button, I am given an opportunity to name and locate my new virtual folder:

I select branches as the location and fill in a name for the target of the copy. I add a message and hit commit:

And there is the new release in the wrong place. I meant to put it in releases. No matter. I just use the svn move button to move the beta1.0 folder to the right place:

Done. Now to work on the beta I check it out, or I can continue working on the trunk. If I check it out I have to create a set up a new build folder for it of course. Here is the current folder tree:

The other parts of this series can be found via the Cocoa page.
Aperture Plugin: Displaying The Image Count With Bindings

To give some feedback to the user I want to include a display of the number of images that will be exported. I can do that by using bindings: by binding text on the window to an ivar in my Random_Wok object.
I create an ivar called imagesToProcess and an accessor to set it:

In -willBeActivated, I add some code to set it up before it is used:
And since changes in the image type (master or version) can change the number of images, I have to set it each time the export type changes:

That is all the code except for this method:

It returns "s" if imagesToProcess is more than one, otherwise an empty string. I need that in order to implement correct pluralization of my display string.
To display the image count on the window I add an NSTextField in the corner like this:

Its value is unimportant because I will be constructing it dynamically with bindings, but it helps to have a descriptive string there. I set up its bindings like this:

The Display Pattern string is what does the magic. Value1 and Value2 are bound to different key paths. The first to the value given by imagesToProcess, and the second to the plural string given by pluralImagesToProcess:

When these are substituted into the Display Pattern string, the result is what the user needs to see how many images are selected:

Because I implemented the accessors and I use them to change the value, bindings take care of doing this display updates automatically. If I select images in Aperture that include some with multiple versions of one master, the image count displayed changes when I click Master and then Version, just as it should.
The other parts of this series can be found via the Cocoa page.
Site Focus: The Hyperjeff Network
It's hard to describe The Hyperjeff Network succinctly. It's a Cocoa site with a huge amount of material. There are links to 17,436 native OS X applications, many with full source. There is an entire page of links to OS X-centrix sites. And don't miss the list of 361 links to articles about programming in Cocoa. Aperture Plugin: Making A Customized Button

The next feature I want to add is a Bagelturf badge that can be clicked to launch a browser to my home page. For that I need a graphic and some way of making a click open a URL. Since the badge won't obviously be a button, or have a button action, I want the cursor to change to a pointing hand to show that it is clickable.
After a lot of messing about with tracking rectangles I discovered that the correct way to implement the pointing hand was by using -resetCursorRects. I have to subclass NSButton and then override -resetCursorRects to define the cursor shape that I want when the cursor is inside my button.
First I drag a button in Interface Builder onto my window and select the Rounded bevel Button type. Then I create a new file and declare it as a subclass of NSButton using this code:

Then I add the implementation code:

To use the custom class in my nib file, I save those files and drag the .h file onto my nib file. This makes the nib file aware of the custom class and selects the class:

Now I can select my button and set its custom class to BTPointingHandButton:

By making a small image in Photoshop that has transparent background and saving it as a TIFF, I can have the image lay on the window background. To add the image to my XCode project I drag it onto the Resources folder and opt to copy it in.

Clicking on the image and using the inspector shows me what is there:

By dragging the image onto the button, the image is automatically set:

And finally I can add an action to File's owner via the attributes pane called bagelturfAction and hook it up to the button with control-drag. To make the action open a URL I add the action code to Random_Wok.m and use NSWorkspace's openURL method:

Done. Now if I hover over the button the cursor changes and a click launches Safari and goes to my home page.
The other parts of this series can be found via the Cocoa page.
Aperture Plugin: Saving The Default Folder

As currently written the plugin defaults to the same folder each time I run it. This is not convenient. There is a very good chance that I will want to go back to the same folder each time, so I added the exported file path to the defaults that are written to a read from the prefs file.
As part of doing that I changed -defaultDirectory to this code:

Here I check to see if the value read from the defaults (_defaultExportPath) is a valid folder using NSFileManager. If it is, then I use it, otherwise I use the built-in default of ~/Documents. This deals with the user moving or renaming the folder between runs.
Another change I have made is to make the Generate button do something. I decided that using the current date and time would make for a good salt value:

And here is the latest interface:

Note that since I am posting this after the plugin was released, this interface design is no longer current.
The other parts of this series can be found via the Cocoa page.
Aperture Plugin: Storing The Settings Between Runs

[Note: my blogging this project is some way behind the development. Random Wok 1.0 has already been released.]
An inconvenience with the current version is that it always presents blank text fields to the user. I would like to store the prefix, postfix, salt, use salt, random format, random length, and alpha case selection somewhere so that their settings are retained from one run to the next.
Implementing this turned out to be harder than I thought it would be. After reading up on NSUserDefaults and looking at several examples, it all looked straight forward enough. But something very odd happened: the values I were successfully saving and restoring between runs was being stored somewhere, but not in the com.bagelturf.Aperture.Export.Random_Wok file as I had been expecting. Not only were they not in the expected file, the expected file did not exist. It was never created.
The values I was storing were actually getting put into Aperture's own preferences file in ~/Library/Preferences. While under some circumstances this would have been the desired behavior (such as writing my own plugins for my own application), in mine it was not. I could not use most of the NSUserDefaults methods because of this side-effect.
So I created two methods: -getDefaults and -setDefaults and inside them used -persistentDomainForName: and -setPersistentDomain:forName to read and write the complete plist file as a dictionary.
Setting the defaults (that is writing the file) is done like this:

It first accesses the shared instance of user defaults and then uses the bundle identifier to retrieve the settings into a mutable dictionary. That dictionary is then updated with the latest values from the ivars, suitably encoded, and written back to the file. This allows older versions of the plugin to work with newer versions of the plist file: anything not used is simply left alone.
Reading the defaults is much more involved. The extra work comes from the need to set up the file if it does not initially exist and to manage plugin version changes. The first part is much like before, with the addition of reading the version from the plugin bundle:

Then I deal with the first run. This is indicated by an empty dictionary:

This results in a file on the disk, and a mutable variable defaultsDict with the same information. Now I am ready to deal with a change of version number:

I have nothing to do: there is only one version so far. If the version has changed, then the new version number is written to the dictionary and out to the file. Finally I am ready to set up the ivars from the dictionary values:

I call -getDefaults from the -initWithAPIManager method so the ivars are ready to go when the window is created. Then in -willBeActivated I set up the various elements of the view:

Finally in -willBeDeactivated I call -setDefaults to write the current state of the interface to the plist file.
Here is what the final com.bagelturf.Aperture.Export.Random_Wok.plist file looks like:

The other parts of this series can be found via the Cocoa page.
Aperture Plugin: Dealing With Duplicate Random Names

Now that I am finally exporting with random file names I feel like I am on the home straight. But there is plenty more still to do: looking for problems, for instance.
There are two things that can go wrong with the export. First there could be an existing file in the folder I am exporting to. This is actually quite likely since repeated exports will create the same names for the same files unless the salt is changed. To solve that I add some code to display an alert if the rename fails. I modify the call to movePath by adding a handler. If there is an error with the rename, the handler method will be called:
