Saturday, June 28, 2008

Fresh from your mom's garden ...

CBC Radio 2 has a very interesting radio show called The Signal which run every day of the week and feature contemporary (& experimental) music from around the world (yes, including Canada). Since the show runs from 10pm to 1am, I'm usually not able to listen to more than 10 or 15 minutes of it (I wishes they had a podcast, or some sort of on demand playback) but it is usually enough to discover a couple of intriguing music, such as the one played last night: The Vienna Vegetable Orchestra which use fresh vegetables from the market to make music. A delightful experience, check out this YouTube video:




Pretty neat eh? :-)

Thursday, June 26, 2008

"Classical" Hip Hop

If you happen to have read my first post on this blog, you already know that I won't be only talking programming here, but that will also blog about other subjects of interest, such as this one. CBC Radio 2 have made available on their Concerts on Demand site, a recording of the concert that Buck 65 have made with Symphony Nova Scotia. Yep, that's right ... an iconic figure of the Canadian Hip Hop scene, with a classical orchestra! Turntable and computer as part of the usual suspects of an orchestra!?? Simply Brillant! I hope this will come out eventually as a CD ... or better, as an iTunes download ;-)

Wednesday, June 25, 2008

To release or not to release? autorelease duh!

Well, it turns out that the standard class methods used to instantiate a new NSException object, send an autorelease message to the object, effectively putting it on the nearest NSAutoreleasePool. As with my earlier issue with the cost of the try/catch block, I was mis-informed :-| ... mind you, I have yet to see any official document clearly stating the memory whereabouts of an exception ...

To release or not to release?

Since exceptions in Objective-C are full featured objects (which don't have to be derived from NSException), it is legit for a code monkey to wonder when are the exceptions ... well you know, released. From what I have seen so far in Apple documents and from (most) code samples I see on the web, it appears as exception object are released automagically at some point ... but are they really? Having derived Cocoa's exception class to add an origin field to it, I also added to my class an implementation of the dealloc method (so that I could release the origin string). For good measure, I also added a printf statement just to verify that the method was been called (e.g I could have goofed up the signature).

As you will have guessed (easy since otherwise I will not be blogging about it), I found out that the method was not been called unless I explicitly send a release or autorelease message to the exception object within the catch block ... (!!?) A quick search on the web didn't yield more details, except for an blog post by Chris Hanson showing an autorelease message been sent from a finally block for a caught exception (however that occurrence is due to him retaining the exception in the catch block, so not really relevant to the case at hand). I'll have to dig this further ...

Tuesday, June 24, 2008

NSObject+CleanupAwareness

To the risk of boring to death my single reader (sorry Usman!), let's continue a bit on the subject of exception :-P Thanks to Objective-C support for categories, it is possible to add shortcut methods to the ubiquitous NSObject class, so that any instantiation of a derived class (virtually any classes of Cocoa) can push and pop itself on/from an existing cleanup stack. And how do we get around of doing that you may ask? Well simply by creating a category of the class:
@interface NSObject (CleanupAwareness)

- (void) pushForCleanupL;

- (void) popFromCleanupL;

@end
The implementing it as follow:
@implementation NSObject (CleanupAwareness)

- (void) pushForCleanupL {

[[HZCleanupStack current] pushL:self];

}

- (void) popFromCleanupL {

[[HZCleanupStack current] popL:self];

}

@end
Then Objective-C will work its magic and any code linked to yours will have it's objects capable of being placed on our cleanup stack. Cool stuff isn't it? At first I wasn't too much excited by Objective-C (its syntax was a little odd for a C++ monkey like myself), but it have definitely grow on me as I got to known it better :-)

If you are, like myself, dying to see the next Pixar movie (this Friday!), be sure to read the review written by (darn) lucky Scott Stevenson on his blog. While you are had it, you may want to also read all the good material that he have written about Cocoa & Objective-C on Cocoa Dev Central.

Sunday, June 22, 2008

Tidying things up a bit ...

The second thing I have been carrying over from Symbian is a mechanism that goes hand-in-hand with exceptions, the (infamous among beginners) cleanup stack. Its purpose is quite simple: insure that no memory will be leaked when exception occurs. In an environment where exceptions are used pervasively (like Symbian), the interruption of the natural flow of execution can easily lead to temporary objects allocated on the heap been orphaned, each constituting a memory leak. The idea behind the cleanup stack (Symbian's style) , is to allow (and actually enforce) programmers to push object on a special stack prior to any call that could throw an exception, or to use the standard Symbian lingo: leave. Once the call has been completed, the object must be popped from the special stack. This sounds like extra work for the developer isn't it? Well, yeah it is a bit more work and a bit more careful thinking, but it is well worth the trouble when the application must run for long period of time on an system where resources are spare (iPhone anyone?).

Originally (well, last week actually ...) I had implemented my cleanup stack as a set of C functions to be called from within a try/catch block. The problem is that thanks to the lack of namespace and functions overloading in C, my functions had the severe tendency to be ultra long. Now, I know about Apple's mantra: "developer spend more times reading than writing code", but still who'll like to have to type this function call hundreds of times per file (yeah , OK I exaggerate a bit about the occurence of such call ...):
HZCleanupStackPopAndReleaseManyWithLastObjectL(...);
So yesterday I started re-implementing my stack as an Objective-C class which allow for more developer friendly code to be written, at the cost of a bit more overhead since messages are to be sent to the stack instead of more efficient function calls. Now, in case you did not follow one of the first page referenced on this post (actually the second one), allow me qto uickly show how the cleanup stack is been used. Let's assume that you need to call a function that is known to leave (following Symbian coding style, the function/method name must be post fixed with an upper case L): doSomeL(). As an experienced developer, you know that you must call this function from within a try/catch block or from another function that is also known to throw exception. In this case, we will use a try/catch block. Your function will be looking somewhat like this:
void doTest()
{
@try {

[HZCleanupStack windUpL];

doSomeL();

} @catch(NSException* lException) {

printf("exception occured\n");

} @finally {

[HZCleanupStack unwind];

}
}

It's contents is simple: at the start of the try block, the cleanup stack is winded-up (created) then the function is called. When the try/catch block end, the stack is un-winded (destroyed). If an object was created (and placed on the cleanup stack) in the doSomeL() function before it threw an exception, the un-winding of the stack in the finally block will release it, serving the purpose it was built for. Let's now have a look at an example of a toublesome function:
void doSomeL()
{
HZObject* lObject[2];
HZReleaseStack* lStack = [HZCleanupStack current];

lObject[0] = [HZObject newLC];
lObject[1] = [HZObject newLC];

someFunctionL(false,lObject[1]);

[lStack popAndReleaseManyL:2 withLast:lObject[0]];
}

Here, we will assume that we have an class of object (HZObject) which will accept the selector newLC as a way of instantiating objects. The post fix LC indicates that the call can throw an exception and that otherwise it will leave the created instance on the cleanup stack. Since the function is known to potentially leave, it is assumed that it have been called from within a try/catch block, thus a cleanup stack is available, the selector current used on the class HZCleanupStack will return it to us (in fact, it will return the last winded stack for the calling thread) so that we can pop the two allocated objects. Now, what happens if this function isn't called from within a try/catch block? Well, the creation of the first object will throw an exception and the object it-self will be released.

If that help, I should maybe mention that the cleanup stack concept is somewhat a kin to a NSAutoreleasePool object with the added ability to push then pop objects at will. Maybe I'll add to this in a following post.

Thursday, June 19, 2008

Be a software slut ...

Catchy title isn't it? Obviously it's an intriguing concept that I took from the hilarious talk (video) that superstar indie Mac developer Wil Shipley (of Omni Group & Delicious Monster fame) gave at the C4 conference in August last year. If you are an indie developer, or if you would like to be, or if you think that you may want to be (but don't know if you can do it), then you most definitely must watch Wil's take on hype (and other things that could potentialy make you successful). I guess, I should also mention his blog, although I'm sure that anyone reading this will have known about it for a while ... unless you are new to the scene (oh man this soooo early 90s! Quick get the Amiga out!). Anyhow, there's a lot of (very) good stuff to learn from that talk, so make sure you have some paper and a pen handy so that you can jolt it all down. How do I know it's sound advices? Well ... he's a successful independent developer, and I'm not. Therefore, what he have to said must be good advices ... unless he's just applying his (core) principles and hyping things ... hmmm 8-o

Wednesday, June 18, 2008

Zero-cost exception! (No, really).

Following up on my post from this morning, it turned out that my hunch was correct. GCC on 64-bit MacOS X, require the -m64 flag to compile x64 code. Once I added it, the try/catch block really did become zero-cost. Problem solved (now what about on the iPhone?) ... as advertised by Apple release note :-)

Zero-cost exception?

Like any code monkey that have been around for a while, I have assembled from my various experiences (BeOS, QNX, Symbian, Win32 ...) a particular coding style and set of paradigms/concepts I like to use for my own projects. When I start on a new platform, I usually have to adapt my style to what is available and/or most commonly used on the platform, and this is usually a good exercise that goes hand-in-hand with learning a new environment. Since I have picked-up the usage of exception for error handling from my mobile development days at Nokia, this is one of the first thing I have been looking at when starting with Objective-C. Now, I'm not going, in this blog, to join the on-going debate raging in the software community about the pros&cons of using exceptions vs. returning error codes, however I should state that I do prefers to use exceptions as they allow for a more elegant and clean (meaning readable) code (IMHO).

After finding a couple of references (can't find the link now) to the fact that Objective-C's exception handling is not as efficient as C++ (meaning not zero-cost), I decided that I should try to check that out. For that purpose I wrote a simple (and naive) test program which measure the elapsed time for a loop calling a function containing either a try/catch block or a old fashion if statement. Here is the function been called repeatedly:
void loop(Foo* aFoo)
{
static int i=0;
#ifdef _EXCEPTION
@try {
[aFoo doSomeL:i++];
} @catch(NSException* lException) {
printf("An exception was thrown!\n");
} @finally {
}
#else
if([aFoo doSome:i++] == NO)
printf("An error occured!\n");
#endif
}
The Foo object here used is of no real importance. In both path the message been sent will compare the value passed as argument and will return an error or throw an exception when an hard-coded value is reached within the loop. Since my immediate concern was the cost of try/catch block, I had set the hard-coded value to be higher than the loop range so that even if the test was been performed at each loop, it will not trigger an error or exception.

I was rather disappointed when I ran the program with if statement then with the try/catch block and noted than the later was 8.2 times slower (without any exception been throw). Since my understanding was that Objective-C's exception handling on 64-bit had been improved compared to 32-bit with 10.5 (see bottom of release notes), I'm definitely surprised considering that I was testing this on an iMac (Intel Core Duo 2, gcc 4.0). Now, it is possible that I'm doing something wrong ... I'll have to double check that I was indeed compiling for 64-bit, which I assumed was the case since I believe that gcc will use this mode per default on a 64-bit machine (at least that's the way it work on Linux).

Since I have easy access to a x64 Linux box (gcc 4.1 with Objective-C support), I quickly adapted my test to the absence of Cocoa and noted with than the cost of the try/catch block was only 1.03 times higher than an if statement ... evidently zero-cost as advertised. So what it's going on with OS-X?

Tuesday, June 17, 2008

Geeky arousal ...

Circa 1990, I believe, my mom brought me to see a doctor for a reason that I have long forgotten. In fact it was a very forgetful event aside for one little thing ... Back then (if you recall), Doctors were very much into Personal Computers (in France at least), they were the early adopters of the digital age yet to come. In fact, they were so much into their computer that for the most part of the visit, they were only looking at their screen, typing away. While waiting in the waiting room, I noticed, casually lying on a coffee table, the (then) latest issue of Science & Vie - Micro (a french magazine dedicated to computers) with on the cover .... a NeXTcube in all its glory! And boy, was that hardware cool and sexy!

Needless to said I feverishly devoured the article, lusting away on the pictures and screenshots of NeXTSTEP in action, and I was amazed and aroused. At that time (I was only 16) my experience with computers have been limited to various BASIC powered "desktop" (Macintosh,Amstrad CPC,...) and pocket computers (Casio FX-702P). If I did program a bit back then (mostly on my pocket calculator), most of my time was really spend playing video games on my bulky IBM PC clone (8088 If I'm not mistaken) running DOS. It's easy to see how NeXT's hardware and OS was very much forward thinking ... It looked not only like something from a science fiction movie, but was also sporting features and a user interface that were very uncommon for the time (at least outside of the universities/multinationals circles). I will love to think that this encounter was the trigger of a closer involvement in computer science ... but I don't think it is really the case. I did start learning the more powerful Pascal language around that time ... but I can't recall if it was due to been aroused by NeXT.

18 years after, I'm finally making the move to NeXTSTEP ... or at least to its descendant, MacOS X. It's not that I could haven't done earlier since we have had an Apple computer for the past 5 years, but the conditions were never really right ...

Monday, June 16, 2008

Bandwith stealer (casual)

Since I was in Victoria all week-end, I didn't manage to continue learning the way of the OS-X platform. However, since I had my iTouch with me, I was able to "steal" a bit of bandwidth from various location ... enough to check a couple of web sites (e.g Slashdot). I don't know if you have travelled to Victoria, but in order to get there you need to take a ferry (1.5 hours) on a very scenic trip. This is usually a good occasion to check out what kind of electronic toys are popular these days. During past trips, I had very often saw many Apple laptops (in majority at time!), but yesterday, oddly enough, I didn't see a single one, only PC laptops and a couple of iPhone and iPod touch and "older" iPods. I think that it will be nice if a wireless Internet access was provided on-board the ferry, however one should really be enjoying the trip from the promenade decks and not be plowing away on a laptop (albeit it should be possible to geek from the deck).

In the past, when confronting with the need to learn a new platform, I have in most case been subject to hard time constraints (e.g day job) forcing me to get up to speed as quickly as possible. However, since my current Cocoa endeavor isn't bound to any particular project (at the moment) I have been taking my time, leisurely (some may said lazily) reading the various documents I have printed-out (sorry, I'm not much for ready PDF on a screen). The thing with Apple documentation, is that it is usually filled with good content, while being also pleasant to the eyes. True be told, I haven't really started reading a document authored by Apple, since I have been reading and older document published by NeXT: Object-Oriented Programming and the Objective-C language. But, I can said that the layout and content are definitly very much akin to Apple's documents (e.g The Objective-C 2.0 Programming Language). Since I'm not even half-way trough the document, and that so far it have only covered the basic OO concepts, which which I'm already familiar, I can't (yet) tell if it is a recommended reading when getting started with MacOS programming. Likely it's an interesting read from an historical standpoint, but likely not a mandatory one since it's a little bit outdated (I believe it is from 1997).

Friday, June 13, 2008

JavaOne vs. WWDC #2

To follow-up on my last post, I wanted to add that WWDC is (obviously) more akin to Google I/O. There again, most (if not all) of the conference contents is available on the web (e.g Android talks). Now, the thing with WWDC, is that all but the keynote is under an NDA. One may wonder why all the sessions/talks at a developers conference need to be protected by such agreement? Does Cocoa 101 really need to be under NDA?

Anyhow ... I'm heading for the passport office this morning (to apply in person). Since I have heard a lot of horror stories about how long the line-up can be ... I'm making sure that I have enough loaded up on my iTouch to last several hours.

Thursday, June 12, 2008

JavaOne vs. WWDC

If I had some readers, I'll probably get a lot of flak about the title of this post. Afterall, JavaOne and WWDC, it's like comparing ... well apple to orange. While the Java event is more about Java technologies and the community, Apple's yearly event is very much focused on offering to developers the opportunity to learn/improve/discover the Apple platform(s). So then, what is there to compare you may ask? Well, coverage and openess of the event. While the WWDC keynote is overly covered both by the press and the attendees (and by Apple), the rest of the week goes by relatively un-noticed and uncovered. Sure, there is a couple of blogs/sites on which (lucky) participants share (a bit of) their adventure (e.g The iLife) but official coverage from Apple is non-existant (please correct me if I'm wrong). A starck difference with what Sun provides online during (and after) JavaOne. Now, I'm aware that attending WWDC isn't free, thus I can understand that sessions material isn't readily available on the web during/after the conference, but I do think that a bit more coverage geared towards the developer that couldn't (but wanted to) make it, could be beneficial to the community IMHO.

Wednesday, June 11, 2008

Vous prendrez bien un bol de cacao chaud?

As you will have guessed (from the title) this is another one of these geeky blogs where the author will be rambling posts after posts on various things including (but not limited to): Mac, OS, iPhone/iPod, Cocoa+Objective-C, programming, gadgets, movies, music ... Well, I think you got the point: heavily geeky stuff.

About two weeks ago, I got myself an iPod touch. The purchasing process by it-self was rather quick (and painless, except for the bank account), however the whole decision process leading to the choice of the latest gadget I should carry around, took weeks... At first, I had set my eyes on a PSP. It sounded like the good blend of gaming, mp3ing, surfing and possibly coding, but then I found out that in order to hack on the device, the battery had to be physically modified (unless that is you get a developer seat from Sony, I presume) ... and that, for a software guy like myself was the definitive deal breaker. Also, during the week leading to my purchase, I managed to borrow my brother-in-law's PSP. The surfing experience on it failed to really excite me (also the text entering method "a la" cellphone is a major pain IMHO), altogether I must said that device is neat ... but definitely not as sweet as the iPod, especially since some good (casual, not hardcore) games are coming out for it :-)

Anyhow ... I'll ramble some more in coming posts on my experience with the iPod touch (thereafter referred as iTouch), but I can said that the whole thing got me to finally join the legion of the Apple code monkeys. Since I have always been (and always be, regardless of the amount of Windows' code I have been coerced into authoring over the years) a Unix guy at heart, switching wasn't much of a big leap ...