Borkware Miniblog

February 1, 2008

Next CocoaHeads/Pittsburgh : Feb 7 – NSOperation

Filed under: cocoaheads — Mark Dalrymple @ 2:57 pm

For folks in the Western PA area, the next CocoaHeads/Pittsburgh will be thursday, February 7. I’ll be talking about NSOperation.

January 29, 2008

Concurrent Programming with Many Mes

Filed under: amosxp, LNC — Mark Dalrymple @ 10:50 am

I had the pleasure of recording another Late Night Cocoa podcast over at the Mac Developer Network. This time I blabbled about concurrent programming, including some chatting about NSOperation.

If you know something about Cocoa programming, I’d like to encourage you to do a LNC podcast. Scotty is a pleasure to work with.

January 21, 2008

Chunky text in Pages

Filed under: amosxp — Mark Dalrymple @ 6:28 pm

I’ve been using Pages for writing new AMOSXP chapters, and for the most part, it’s a pleasant experience. I’ve just about got the NSOperation chapter put to bed, and was making a PDF to send off to the first round of reviewers, when I noticed the generated PDF output was beyond horrible. Here’s what it looked like on-screen:

Picture 19.png

and here’s what the resulting PDF looked like:

Picture 18.png

Hideous, isn’t it?

Turns out that Pages is honoring the “Turn off text smoothing for font sizes x and smaller” when generating the PDF, and using bitmaps for the smaller font sizes. I have that set to “12 and smaller” because anti-aliasing plus my eye correction conspire to make things difficult to read. Why Pages is using this setting for PDFs is beyond my comprehension (and I hope it’s just a bug – VoodooPad does the RightThing. Filed Radar 5698417). You’d think that PDFs are being made for someone else’s consumption, and so wouldn’t carry along personal preferences like this.

January 20, 2008

Release In Order

Filed under: programming — Mark Dalrymple @ 4:51 pm

My cow-orker, Mike Morton, gave me a little bit of advice over a year ago that’s proven to be incredibly useful: “In your -dealloc, release objects in the same order they’re listed in the @interface“. This makes it really easy to double-check your work and make sure you’re releasing everything you need to. It also makes maintenance easier: skim down your -dealloc and compare to your @interface before you land your code.

January 16, 2008

Macworld 2008

Filed under: Random — Mark Dalrymple @ 10:33 pm

View of the show floor.jpg

It’s Macworld 2008 time. I had Google Booth Bunny duty on tuesday. When I wasn’t working the booth, I wandered around the show floor with a camera, with the obligatory web gallery.

October 31, 2007

Exploring Leopard with DTrace

Filed under: programming, work — Mark Dalrymple @ 4:39 pm

My friend and cow-orker Greg Miller has a piece published at MacTech: Exploring Leopard With DTrace.

DTrace is cool. DTrace is awesome. Go read this.

October 29, 2007

Speed Download for Apple Seeds

Filed under: irc, Random — Mark Dalrymple @ 10:25 am

Apple provides downloads for OS X version for developers with seed keys. That’s cool.

Apple’s webservers cut off long downloads after twelve hours. When it takes twelve hours and fourteen minutes to download something, that’s not cool. I don’t want to think how many multigigabytes I downloaded before figuring out that twelve-hour cutoff.

Jonathan Wight said on IRC one day, “dude, use Speed Download“. I did. It works. I watched the progress meter at 12 hours. download speed went to zero as expected. A couple of seconds later it cranked back up Fourteen minutes later I had a finished download. That’s cool.

October 26, 2007

ZeroLink, Rest in Pieces

Filed under: irc, programming — Mark Dalrymple @ 11:28 pm

6FF1A549-451F-4BCB-9EB5-3317786D19E3.jpg

One thing that made me happy, and was greeted with applause at WWDC, was the news that ZeroLink is gone in Leopard. The linker is now fast enough to make ZeroLink unnecessary.

So what was so bad about ZeroLink? The first problem wasn’t actually ZeroLink’s fault – it was Apple making ZeroLink on by default for new Xcode projects. A common refrain heard from new Mac programmers was “I made a Cool Little Cocoa App, sent it to a friend it won’t work for him. What’s wrong?” ZeroLink.

ZeroLink performed its magic by demand-loading object files, and those object files weren’t included in the application bundle until several Xcode revisions later. So sending an App to a friend (or a reviewer, or a cow-orker) would mean sending them a broken app. Then the programmer would ask for help on a mailing list or IRC, get told to turn of ZeroLink, and then rebuild and re-send. In fact, the Feenode #macdev FAQ has a special section just for ZeroLink.

This was embarrassing and demoralizing, especially for someone new to the platform. New, small projects didn’t benefit from ZeroLink anyway, and you have to have a pretty large program before the time savings is noticeable. Someone with a project that big will have someone intimate with Xcode who would know about ZeroLink, so need to have it on by default.

The second problem was that ZeroLink introduced instability, with its frequent refrain being “I’m getting weird crashes”, which are fixed after turning off zero link. I got paid for a full day’s consulting tracking down a strange C++ operator new overload. The daily smoke test built and ran great, but development versions crashed and burned in weird places. We finally tracked the main difference between the developer builds and the automated builds: ZeroLink. Turned it off, rebuilt, and life was happy ever after. This particular app (which was freaking huge) was broken down into lots of frameworks, so link time wasn’t that much longer than with ZeroLink. (Because of this framework breakdown, I was able to pull some command-line tricks to prevent unnecessary recompilation of other parts of the system, and greatly reduced my turnaround time on a TiBook500 vs the G5-weilding full-timers, but that’s a story for another day.)

Good bye ZeroLink.

NSCoder Night

Filed under: cocoaheads, Random — Mark Dalrymple @ 10:40 am

Chris Hanson and Scott Stevenson are organizing NSCoder Night in the Silicon Valley, a weekly event where Cocoa geeks can hang out for coding and mayhem at a coffee shop or a pub. It sounds like it’ll be a huge amount of fun.

For folks in the Pittsburgh area, Jeff Hunter is organizing DevHouse Pittsburgh thursday the 8th. It’s similar to NSCoder and SuperHappyDevHouse, but in the pittsburgh area. Some of the local CocoaHeads will be there.

October 4, 2007

Pittsburgh CocoaHeads

Filed under: cocoaheads, programming — Mark Dalrymple @ 10:03 am

FDF2963A-3D56-4EE3-8A46-74A6D6ACA7FB.jpg

After about a year off, Pittsburgh Cocoaheads is going to be starting up again. Second thursday of the month, 7:30 – 9:30 PM, on the CMU campus (Newell-Simon Hall. Room 3000 or 3001. There will be signs pointing the way)

And for folks who don’t know about CocoaHeads, it’s an international Mac Programmer’s group. Pretty much an excuse for Mac programmers to congregate and geek out. Right now we have 20ish chapters in seven countries, two hemispheres, and four continents. Check out CocoaHeads.org for a chapter near you. If there is no local chapter, or if your local chapter hasn’t met in awhile, feel free to drop us a line and become an organizer.

CocoaHeads started in Pittsburgh several years ago when AgentM and I decided to start a Mac programmer’s group because there was nothing in the area. He came up with the name and the logo, and did a lot of evangelizing in the early days. I’m glad AgentM picked the name : I would have come up with something horrible like “Western Pennsylvania Mac Programmer’s Geeking Out And Food Eating Society”, which doesn’t quite have the groovy ring of “CocoaHeads”

September 29, 2007

Don’t Forget VoodooPad

Filed under: amosxp, programming, Random, work — Mark Dalrymple @ 3:57 pm

With all of the love and attention that Flying Meat’s Acorn is receiving, I figured I would remind folks about VoodooPad.

VoodooPad is a personal Wiki that lets you write stuff and link things around. When it sees words in CamelCapsStyle, it automatically turns it into a link to a new page where you can write more stuff. All pretty standard wiki stuff. It uses the OS X text engine so it has all of the standard word processing features you’ve come to expect, including stuff like tables and lists. This is especially nice because I get a lot of my emacs key bindings along for free. Muscle memory is a wonderful, wonderful thing.

Screen Capture of VoodooPad pro

There are a couple of things I love about VoodooPad : it gets out of my way. I type, I link, I paste in graphics. Gus has obviously paid a lot of attention to the fine details and the app just gets out of my way. It is also very stable. I don’t remember when my last crash was. It just works. Just about every Leopard update makes SnapZ pro freak out and I have to get get new license keys (and then usually something fails on the server side, and takes 20 minutes of dinking around to get a license). Omnigrackle‘s layers get confused and the PDF export dialog has a bug that makes it easy to corrupt your document. Mail.app regularly crashes. But VoodooPad just keeps on chugging along. Oh, and it’s fast, too.

Some folks I know put everything into a single VoodooPad document and use it to store their life (or at least their brains). I typically have one VoodooPad document per project, which usually fall int into one of three broad categories:

Design Document : I have one where I keep my design notes for the Extreme Cross Stitch Design software I’m working on for the Spousal Overunit. I dump figures from OmniGrackle in there, and use class names as the currency of links. This makes it very easy to capture my thinking about the specifics of individual classes, as well as highlighting the interactions between classes. Sometimes I can go for a month or two between working on the App, so having all this stuff handy and interlinked makes it easy to reload my mental state. My winning IronCoder entry included a VoodooPad design document with all sorts of notes. (The entry was Race Against Time, if you’re really bored)

Data Dump and Organizer : I have another one where I keep all my notes, to-dos, transcriptions, and copies of interesting emails for the next edition of AMOSXP. You can see a screenie for this is over to the right. I blort in anything and everything I think might be interesting for the next edition. As I start chewing up a chapter, I have ready access to stuff to consider for exclusion (and stuff to nuke). Sometimes one topic (say an extension to a favorite object-oriented language) is too big for one chapter, so something like its automated memory management technique would make better sense living in the Memory chapter. So I can easily make a note in MemoryChap to say “go look over InThisSetOfNotes for these aspects of rubbish aggregation that would be interesting to talk about here”

Debugging Aid : For projects where I tend to do more debugging than design, I have a VoodooPad document that keeps my debugging notes. Usually for each non-trivial problem there’s a page with a dialog with myself. “So What’s the Problem Fool? Oh, Google Kipple is crashing when you frobulate the giznat. Does it happen all the time? No, just on the second launch. Maybe it’s the SpicyPonyHead user preference Hrm, could be” The dialog format lets me focus my thoughts by making explicit what the next useful piece of information might be, and it makes for easier reading when I need to revisit a bug or if I have to put it down for awhile and return to it later. The linky nature of a wiki makes it easy to put in different branches of investigation and let me revisit what I originally thought was a dead end, but might actually be the path to figuring out the real problem. Because Cocoa class names are CamelCapStyle, class names in stack trace become links. Ppaste in a stack trace and then link out to a class to jot down some relevant notes.

I’m a fan. Check it out.

September 27, 2007

Ten Tips for a (Slightly) Less Awful Resume

Filed under: Random, work — Mark Dalrymple @ 9:42 am

Steve Yegge knows hiring. His latest epistle is Ten Tips for a (Slightly) Less Awful Resume.

Rands also has a new article about The Button, the personality types you’ll run into during technical interviews.

September 13, 2007

C Callbacks in ObjC

Filed under: amosxp, irc, programming — Mark Dalrymple @ 11:23 am

It’s interesting to see common subjects come up in the IRC channels. When someone unfamiliar joins and asks the question “how do I put a method into a function pointer?”, 9 times out of 10 they’re actually wanting to use Cocoa with an existing C API that uses callbacks. A much better question would be “I’m using a C API that uses callbacks with Cocoa, how do I make it work?”

The Answer

You can’t use Objective-C methods as callbacks. Stop trying, you’ll just make yourself angrier. You have to bounce off of a regular C function, and use any “userData” or “info” mechanism in your C API to pass a pointer to your object.

So assuming you have a call SetDrawingCallback, which takes a function, but you actually want to draw using your objecty-goodness OblateSphereoid object, you would do something like this:

BWOblateSphereoid *egg = [[BWOblateSphereoid alloc] init];
 
SetDrawingCallback (drawingContext, /* context that wants to draw */
                    drawEggThunk, /* the function that the context will call */
                    egg);  /* arbitrary userData pointer */

Then in your callback function:

void drawEggThunk (DrawingContext *context, Rect areaToDraw, void *userData)
{
    BWOblateSphereoid *dealie = (BWOblateSphereoid *)userData;
    [dealie drawAnEggInRect: areaToDraw];
} // drawEggThunk

You are allowed to call Objective-C methods in a C function. You just need to make sure your file is compiled as Objective-C, whether you have a .m extension, or tell Xcode to compile it as Objective-C explicitly. If your callback API doesn’t let you pass in a userData pointer (a rock to hide your data under), you’ll have to put your object into some global location for your C function to find.

If you need to poke inside of the object directly, you can put this function inside of the @implementation block of your class, and then you can access instance variables with the C arrow operator. But that’s kind of naughty, so to preserve your Purity of Essence you should be using method calls on your object. End of Sermon. Here’s the evil:

@implementation OblateSphereoid
 
void drawEggThunk (DrawingContext *context, Rect areaToDraw, void *userData)
{
    BWOblateSphereoid *dealie = (BWOblateSphereoid *)userData;
    dealie->_frognatz = [NSColor plaidColor];
    // and more stuff.
} // drawEggThunk

...
@end // OblateSphereoid

Why?

So why can’t you just (somehow) get the address of -drawAnEggInRect: for the BWOblateSphereoid class and pass that for the drawing callback? The answer is a secret. Two of them, in fact.

When you use brackets in Objective-C to send a message to an object, the compiler is actually generating a call to the C function objc_msgSend (or to one of its variants, but let’s keep it simple):

id objc_msgSend(id self, SEL op, ...);

So something like [egg drawAnEggInRect: someRect] turns into:

objc_msgSend (egg, @selector(drawAnEggInRect:), someRect);

Which then calls drawAnEggInRect:, which under the covers boils down to something like this:

void drawAnEggInRect(id self, SEL selector, Rect someRect) ...

self and the selector are passed in as secret hidden parameters, and then any arguments for the method follow them. This is why you can’t just use the address for a method’s code in a C callback API. The library code invoking the callback will be wanting to put its own stuff in the first couple of arguments, which will cause all sorts of nifty explosions when Objective-C starts interpreting those as object pointers and selectors.

September 6, 2007

It’s Still Just C – arrays and pointers

Filed under: irc, programming — Mark Dalrymple @ 8:35 pm

Another fine day on IRC. An individual was stating that you couldn’t pass C arrays to Objective-C methods. That surprised me, so I wrote a little little command line program to check (the program is at lisppaste.) Of course, it turns out you can – Objective-C is still just C. And because it’s just C, you have the behavior of arrays and pointers being pretty much interchangeable.

For instance, you can pass a C array to a method:

- (void) ookie: (int *) snork {
    NSLog (@"%d %d %d", snork[0], snork[1], snork[2]);
} // ookie

Or use the [] syntax:

- (void) ookie2: (int[]) snork;

or use the explicit size syntax (which doesn’t really matter for 1-D arrays):

- (void) ookie3: (int[17]) snork;

And you can pass in pointers to pointers to pass back a resized array originally allocated by malloc:

- (void) ookie4: (int**) snork
         growTo: (int) elements {
 
    *snork = realloc(*snork, sizeof(int) * elements);
    (*snork)[0] = 55;
 
    NSLog (@"(%d) %d %d %d", sizeof(snork), (*snork)[0], (*snork)[1], (*snork)[2]);
 
} // ookie4

Passing in arrays of Objective-C types isn’t a problem either:

- (void) ookie: (NSString **) snork {
    NSLog (@"%@ %@", snork[0], snork[1]);
} // ookie

Just make sure your syntax is declaring the original array is good:

NSString *blargh[] = { @"oop", @"ack" };

(the original poster had confusion about Objective-C objects needing to be pointers, having a declaration of NSColor blargh[] = { ... }; and then stating that things aren’t possible)

It does go without saying that you should prefer NSArray, or another collection class, to naked C arrays. Sometimes you need to use the lower-level mechanisms, so the power (and pain) is there if needed.

September 3, 2007

TLAs: VNC & FUS

Filed under: Random — Mark Dalrymple @ 5:21 pm



As part of my day-to-day work, I need to test my software with both admin accounts and non-admin accounts. Fast User Switching (FUS) is nice, for awhile, but it really started to get on my nerves. For one, I’d miss out on real-time entertainment from the company IRC channels. Then there’s the entering of passwords, and waiting for the Big Spinny Cube Effect. These are annoying, but livable.

The big thing is that in some wireless / VPN situations, the net connection would be available in one user but not the other; or the FUS act would disconnect me from the network or the VPN. And since I’m hitting internal resources for testing, this was totally Not Good.

BarryJ, (via my pal Mr. Machine Tool), pointed out that when you switch users with FUS, a window server and a pasteboard server are left running. This means that you can VNC from one user to another already logged-in user on the same machine.

It’s not perfect (the switched user might not be able to log to the console), and sometimes things lock up if I leave it running overnight, but it’s good enough for me to do my work with multiple user accounts and not have to actually FUS between them.

I use the Vine VNC server, and Chicken of the VNC client.

For the server, the changes from the default settings are setting a password, only allowing local connections (which requires SSH to be running). On the client, the host is localhost. So then FUS to the test user and crank up the server. FUS back to the primary account, and then start the VNC client.

September 2, 2007

Link Grab-bag

Filed under: programming — Mark Dalrymple @ 4:09 pm

In doing research and random surfing, I come across some intereting tidbits:

TN2124 : Debugging Magic – a must-read.

Improving your software with static analysis. Not really Shark-style static analysis, but more about using compiler flags to tweak the warning levels. I’m a firm believer in cranking up the warning levels using useful warnings (for instance, -Wunused-parameter is pretty much worthless)

LaunchD user agents are broken in Tiger

Also, the paper Setuid Demystified (PDF), while not OS X specific, does give some insight on how the unix setuid mechanism, how it works and its history.

August 30, 2007

Saving my Beacon

Filed under: Random — Mark Dalrymple @ 8:28 pm

I have a love/hate relationship with the MacBook keyboard. I really like the feel, but when I come to the MacBook (personal machine) keyboard after using the MacBookPro (work machine) keyboard (which I like even better), I have a hard time adjusting. In short, my typing is utter and total crap because I hit the corner of keys, which register a keypress by feel, but it doesn’t actually engage the key switch. This makes me sad.

On a whim, I picked up the Mavis Beacon typing tutor thing at the apple store (after going there to caress an iPhone in person). It’s an old, cheesy program, and some of the “games” are embarrassingly awful, but after doing a couple of basic typing exercise, I have the MacBook keyboard “feel” back again, and my typing accuracy improves a whole bunch. Which makes me happy.

August 25, 2007

It pays to kiss-up

Filed under: Uncategorized — Mark Dalrymple @ 2:08 pm

Emperor Darth Jalkut of the Red-Sweater Empire recently plugged my humble miniblog. My feedburner reader stats went from 84 to 268 overnight. It took long enough to get my mom to subscribe 81 times, so it’s not her that’s doing it. So thanks to D.J. It pays to kiss-up to famous online personalities.

P.S. Mars Edit is still cool.

In praise of little command-line apps

Filed under: irc, programming — Mark Dalrymple @ 1:54 pm

Folks who have hung around with me know I’m an emacs weenie. It’s not that its necessarily the best tool in the known universe, but it’s what I’ve been using for 17+ years as a paid professional on a number of different platforms, and I’ve developed a number of workflow habits that give me the illusion of being productive.

Central to my daily workflow is having several shell buffers open in my emacs session. This means I can boing from a source file to a shell with a half dozen keystrokes.
One side effect of this is that I can create, use, then forget about little command-line programs extremely quickly. They become great little testbeds. No need to create an Xcode project, or create an Executable in an existing Xcode project. I understand that BBedit and Textmate let you run shells within the editor without any extra baggage, which is all kinds of awesome.

One day on the #macdev IRC channel, someone was complaining (gee, that never happen!) that they tried to NSLog a dictionary, and It Didn’t Work. Someone else, who is ordinarily always correct, suggested that NSLog might send -description to the first argument. I didn’t think so, but wasn’t sure enough to argue. So I hopped over to Terminal, made a little program, and tried it out. Turns out you get a compiler warning if you pass a non-NSString to NSLog, and then the program gets an exception when NSLog tries to send -length to the passed-in object.

Knowledge gained in under a minute.

And now I’ve burned an hour writing about it. Oh well. But I’m waiting on a flight, so it’s time better spent than reading yet another Lord Peter Wimsey novel.

Here’s the program:

#import <Foundation/Foundation.h>
 
/*
gcc -g -Wall -framework Foundation -o logger logger.m
*/
 
int main (void) {
    [[NSAutoreleasePool alloc] init];
    NSDictionary *arg = [NSDictionary dictionary];
 
    NSLog(arg);
 
    return (0);
 
} // main

And it took about a minute from initial question to the acquisition of knowledge, including fixing a syntax error. More sophisticated test programs may take longer, but usually not that much longer.

I do this kind of stuff when playing with a new Cocoa class, too. It’s much easier to cook up a little ad-hoc test case to verify my understanding of some aspect of NSWhatever than to try to scaffold something in a big application.

OK, so what are the important highlights of the code? The first interesting bit is the compile line I’ve got in the comment. Having a compile line in each source file makes it easy to find the file, copy out the compile line, paste it into a terminal and go. No need to modify a project or a central makefile (although those studlier than I with makefiles could make an implicit rule for *.m files, but I’ve already have enough scar tissue on my soul courtesy of make) This also makes it handy for folks who are looking at the code after you put it into a pastebin. No need for them to figure out how to run it. Just save the text, copy the command and then paste it into Terminal.

For folks not familiar with the gcc command, here are the moving parts:

  • gcc : run the C compiler. If you’re doing C++, use g++
  • -g : turn on debugging. You might need to run your program in the debugger.
  • -Wall : turn on a bunch of warnings. If your code has any warnings, don’t ask anyone for help until you fix those warnings. To do otherwise would be rude. Although it’s ok to ask for help if you’re having trouble figuring out what a warning means.
  • -framework Foundation : use the Foundation framework. This lets #import <Foundation/Foundation.h> work, and also satisfy the linker when you use Foundation functions and classes. If you’re using AppKit too, then use #import <Cocoa/Cocoa.h> in the code and -framework Cocoa on the command line.
  • -o logger : create an executable program called logger. If you omit this, the incredibly obvious name of a.out is picked by the compiler.
  • logger.m : the source file to compile.

After that comes the main() function. You don’t need to declare argc and argv if you’re not interested in the command line arguments. After that I usually make an autorelease pool, and then the stuff I want to test. main requries a return, so you gotta add one, or else the compiler will whine at you.

You may have noticed I didn’t use a template file with all this boilerplate stuff already filled out. It’s just a personal weirdism I guess. It takes me longer to find the file, edit the parts that change (whether to use Foundation, Cocoa, or neither; the file name; any additional complier flags like -D), and navigate around than it does to just blort out everything linearly. But I’m a very fast typer and don’t like to wait for personal pipeline stalls when having to make decisions.

Many of the examples in AMOSXP are like this — small stand-alone programs that explore one thing. I’m not sure which came first, doing all of the examples, or using small apps to test something I need to figure out. But no matter where it cam from, I’m a big fan of the technique.

August 24, 2007

ObPhotoAlbum

Filed under: Random — Mark Dalrymple @ 11:24 pm

I promise to keep the non-programming content to a minimum (I’m sure many folks tune right out when camera nerds start talking). But I figured I’d point folks to my photo album: http://picasaweb.google.com/borkwareLLC.

August 23, 2007

Book Mania

Filed under: amosxp, programming — Mark Dalrymple @ 11:38 pm

Thanks to Vinoodle for pointing me to Antonio Cangiano’s blog, and A preliminary review of three Cocoa and Objective-C related books., where he has some very kind words for AMOSXP.

One book I like to point folks to, particularly folks who already know how to program and/or already know C (which don’t always necessarily occur at the same time :-), is Andrew Duncan’s Objective-C Pocket Reference If you can find it, that is. I see with horror that it’s currently unavailable via Amazon and Barnes’N’Ignoble.

It’s a mercifully short book, especially compared with the giant C++/Java in a NutCaseShell books, and it hits the important goodies that Objective-C adds. It even talks about the extra syntax relating to Distributed Objects.

I also have to plug Learn Objective-C on the Macintosh (a.k.a. LoC), co-written with Scott Knaster. What many folks don’t know is that Scott’s early Macintosh books in the mid to late 80’s were some of my main inspirations for becoming a professional programmer, and a Mac programmer in particular. I pretty much owe my career, and my current gig at Google, to Scott. I had a chance to meet him at a Big Nerd Ranch course a couple of years ago, discovered he’s a really great guy, and eventually we ended up collaborating on LoC (oh man was that fun). I figured out what we were covering and blazed the main trails, and he made it understandable and fun to read.

If you’re already slinging bits and swizzling IMPs then LoC will be too basic for you. Otherwise, check out the sample chapter and see if it speaks to you. If you’re truly coming up from scratch, you might want to start out with Dave Mark’s Learn C on the Macintosh (LoC is designed to pick up where LearnC leaves off, and Dave was the editor for LoC), and there’s also Stephen Kochan’s Programming in Objective-C, which Antonio also reviews. (I liked it, but I’m a pretty nerdy bookworm.)

August 22, 2007

Movies as Bug Reports

Filed under: Random — Mark Dalrymple @ 12:06 am

Sometimes when I’m building a bug report for somebody, I’ll make a movie of the application misbehaving. A picture is a thousand words, so a movie is at least 15,000 words a second.

For instance, I saw some strange behavior in Mars Edit’s preview panel with a <pre> block. I could spend a chunk of time describing the behavior, and even then would probably omit some important piece of evidence. Instead, I sent This Movie on to the Red Sweater Empire. DCJ asked me to try some stuff, we narrowed it down to line break conversion, and I found a work-around by putting in a space character in the <pre> block.

Similarly, we have an internal tool at the GOOG which I had difficulty getting working. I made a quick movie of it not working, sent it on to the developer, and he said “huh. you’re doing everything right. Lemme go look for the problem.” Sure saved a lot of back and forth, and also saved a lot of wondering “Is this a PEBKAC problem?” (I’m the first to admit I do stupid stuff.)

Naturally, include a link to the movie in any bug report. Sending someone ten megabytes in an email without prior warning could be interpreted as rude.

There are a number of screenShotMovieMakers. I’ve used SnapzPro for years, and have certainly gotten my money’s worth.

August 20, 2007

Daring Fireball, the TV Show?

Filed under: Random — Mark Dalrymple @ 11:57 pm

http://video.google.com/videoplay?docid=4641800997253041180&q=macgruber

August 19, 2007

Objective-C is Stupid (but I still like it)

Filed under: irc, programming — Mark Dalrymple @ 6:47 pm

One of my guilty pleasures is hanging out on Mac programming IRC channels (#macsb and #macdev on irc.freenode.net) Occasionally an interesting discussion erupts over some esoteric topic, but for the most part it’s ordinary questions about the basics of Cocoa programming.

One misconception about Objective-C that comes up occasionally is the assumption that Objective-C does more than it does. In particular things like


“I compare two strings/objects/dictionaries with ==, and the test fails. Cocoa is broken!”
(quickly followed by the Mac sucks, Xcode blows goats, and so on)

or


“Can I concatenate two strings by using + ?”
(quickly followed by the Mac sucks, Xcode blows goats, ObjC2 should have gotten operator overloading, and so on)

Objective-C is a pretty old language, predating Java, Perl, Pythong, Ruby, and many of the modern features of C++. It is just C with a couple of extra knobs on it, with very little extra behavior added to the language. All of the magic is in the runtime which does message dispatching. There is no operator overloading in the language. Pretty much all the language lets you do is interact with integer and floating point values, and calculate addresses via pointers and offsets. In C and Objective-C, there is no implicit complex behavior hiding behind the operators.

Now, folks who come from VB (I presume), Java, scripting languages, and C++ expect things like the == operator to be an equality operator, knowing the contents of the objects being compared; or expect the + operator to be a concatenating operator, dynamically creating objects.

Think about what happens under the hood: comparing two strings compares each of the characters in the string (looping over the contents), or comparing two dictionaries would compare each of the elements in the dictionary (looping over the keys). Likewise, to concatenate two strings, you’ll probably be looping over the two, or allocating blocks and using a memcpy()-like operation. (and in general, using concatenation to build strings can bite you when you go to internationalize your application)

C and Objective-C don’t do anything that convenient. All == does is compare a small number of bytes for an address when dealing with pointers or an integer/float value. And when you come down to it, those are the same operation. In particular, no looping. All + does is add two values. In particular, no allocations.

So, when you’re dealing with Objective-C, and things don’t behave the way you think they should, consider what’s going on under the hood:

NSString *thing1 = ...;
NSString *thing2 = ...;
 
if (thing1 == thing2) {

This is just pure C right here (no @‘s or []‘s are involved, so the Objective-C part of the world doesn’t kick in. No ()‘s involved, so no function calls are happening. Therefore, only a small number of bytes are involved. Each string could be megabytes long, but the comparison will just be four bytes (eight bytes on a 64-bit system). So this is just testing whether one address is equal to another address. An “identity test”, vs a test for equivalency, which is what the programmer probably wanted in the first place. Assuming that the two strings are not pointing to the same @"literal NSString", these will have different addresses, and the comparison will be a false one. (it’s not my nose, it’s a false one)

Now this code:

if ([thing1 isEqualToString: thing2]) {

Does do an equivalency test. Since you’re actually invoking a method here, and methods are arbitrary code, this has the opportunity to loop through the strings and compare them character by character.

So the moral of this poorly-organized story? C is dumb about data. It only does a few blindingly simple things. Objective-C is a very thin layer on top of C, and adds nothing to the existing C syntax. If you’re getting unexpected results with the built-in operators, you’re probably assuming the base language is doing more than it should, and you should update your expectations appropriately.

And while I’m thinking about it, I’m quite glad Objective-C does not have operator overloading. The gotchas are just too subtle, and I don’t mind trading some extra typing or an explicit function or method call in exchange for not having to track down subtle changes in behavior when some class I’m using decides to overload an operator. Hint: in C++, how does operator&& change behavior when it’s overridden, vs the compiler default? You’d be surprised how many experienced C++ developers don’t know that bit of trivia.

If you really want operator overloading (it does make sense in some situations, like the canonical matrix libraries everyone seems to be writing, or at least using for examples of why overloading is a Good Thing), there’s always Objective-C++.

August 18, 2007

Rich Programmer Food Resources

Filed under: programming — Mark Dalrymple @ 5:07 pm

Steve Yegge has a posting about Rich Programmer Food, which boils down to “if you know how compilers work, you can become heap big powerful programmer.” (I find most of Steve’s non-fiction to be interesting reading. The fiction and allegories I can never read all the way through.)

I asked Steve if he had any particular resources to recommend, and he didn’t have a “go here for enlightenment” pointer (short of “write your own language, and you’ll eventually have to learn everything you need to know”), but here are some books and things that Steve and others have recommended to me. I have not read most of the books, so apologies if you get them and they end up sucking.

« Newer PostsOlder Posts »

Blog at WordPress.com.