The phone’s ringing but nobody’s home

You know what I like about Objective C? When you send a message to nil. You know what I hate about objective C? The phone ring’s but nobody’s home. Think about this a minute. Imagine if you were to dial your loved one and mistake a “4” for a “5”. The house you dial has no answering machine/service/secretary. You have no definite way of knowing that you dialed the wrong number or that nobody’s is there. All you know is that you always call at exactly 12:15pm during lunch after taking the 5th bite of your usual Chicken Cordon Bleu sandwich which you order daily from the same fast food provider (paid for by pulling what appears to be the same $10 bill creased in exactly the same corner out of your trusty tattered wallet then after reaching the door doubling back as you always do because you left your keys on the counter). You know your loved one always answers on the second ring and has no reason/desire/ability to suddenly dodge your usual 12:15, “How’s your day going? No, how’s YOUR day going sweetie?” exchange. You hit redial a few times to the same non-response and rather than accept the obvious fact you begin to panic. Something must be wrong! You verify every other point of failure except for the most obvious, calling other family/friends, contacting your building admin (y’all did pay the bill right?), even going as far as arguing with your communications provider(s) in a frantic attempt to resolve an inconsistency or ripple in your otherwise pathetically inevitable daily episode. (You were born with a slight undiagnosed touch of autism which not only hobbles you with predictability and inability to handle subtle changes in your routine but gives you a certain advantage in the field of software design which is roughly 90% about patterns.) After becoming Ralph Tresvant (featured in the clip below) and losing to the unlimited powers of the Verizon network (how come they always get over?) it dawns on you to finally attempt manually punching the memorized phone number into the keypad after which you finally get your much anticipated response, “How’s your day going?”

That’s kinda a little bit sorta like how I might have felt today after I spent 2 hours, 37 minutes and 17 seconds chasing an error where I forgot to set an instance variable in my Objective C class. A creature of habit, I like my runtime to yell at me when I access a null pointer! I love the freedom from these ambiguous errors but hate the flip side. You can go on willy nilly sending all kinds of messages to null pointers, non-objects, empty stuff and not know until three months after you’ve been workforce-reduced after slipping 5 months past a dead line while you spent 4 months and 28 days chasing a production day behavior oddity that just seemed impossible.

Bill Dudney said something like, “It’s not the learning curve that hurts it’s the unlearning curve” and I totally agree. I love/hate Objective-C and I could spit bullets at Steve Jobs for his take on Java and the arrogance of insisting his favorite programming toy should be everyone’s favorite programming toy. As much as I hated picking up yet another language/framework/way-to-do-things I forced myself on because to get hung up in any one tool-set or programming paradigm is to slowly reduce yourself to a collection of the basic carbons and minerals that make jelly-fish wiggle in the ocean. Lesson learned overall. Now I stand as I speak, “My name is Cliff, and I made a call to an empty residence.”

When the triangled shape doesn’t fit in the round hole

I’m writing some iPhony stuff while thinking in Java. I wanna stream an HTTP request over the wire. In Java I’d inject an OutputStream into my class or method and just start writing to it byte by byte. Objective C Cocoa wants to set up RunLoops, setup delegates, and rely on callbacks that pass buffers into the NSOutputStream API. I set on fire and jumped through all of these hoops (after dousing my briefs in Kerosene) but I’m still not getting any data on my stream! Is it because I’m trying to force things to work like Java? Help?

Here’s my test method and impl logic:

-(void) testStreamWriting {
	NSOutputStream *stream = [[NSOutputStream alloc] initToMemory];
	[stream setDelegate:myStreamDelegate];
	[stream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
	[stream open];
	NSData *_data = [stream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
	STAssertNotNil(_data, @"Stream delegate should have written data");
	[stream close];
	[stream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
	[stream release];
	[data release];

@implementation MyStreamDelegate
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
	switch (streamEvent) {
		case NSStreamEventHasSpaceAvailable:
			const uint8_t stuff[2] = {1,2};
			[theStream write:stuff maxLength:2];


OCMock Works in an iPhone Project!

I hit a bit of a snag getting around the “image not found” error when I tried to bring OCMock into my iPhone dev work. (I’m using Google’s iPhone testing tools here.) Between various searches I found a few more people having the same trouble while one or two claimed success. So I didn’t give up hope. I finally tripped and fell into Mitch’s World and found my answer! Thanx Mitch! The solution is to add/copy the OCMock.framework folder into /Library/frameworks and reference it from there. It feels like such a hack and I know I’ll get into trouble this way but it got my tests running again!

Meant to add a link to this page. These Atomic guys seem like they can put a spin on the whole iPhone SDK experience.

iPhony Development – Unit Testing?

I’ve been at it all weekend. Off and on, spawning threads, updating a dumb UI, now exploring Test Driven Design with Cocoa. Here’s an interesting tidbit that I turned up somewhere in the Apple docs last night. (It was past 12am when I read it, I was tired and now I can no longer find it so I might as well be lying to you but…) “Creating unit test targets is not supported for iPhone development…” or so the text read. Why is it that the mobile community thinks they’re so special? Why do they not need unit tests for their software? Am I missing something? I found an article demonstrating how to Test Drive a TicTacToe game in Cocoa and so far it’s been working pretty well. I’m still hitting my random stumbling blocks here and there. My latest blocker comes from the following test auxillary method:

- (void) assertWinnerIs: (int) expectedWinner withMoveInRow: (int) row andInColumn: (int) col {
	int actualWinner = [game makeAMoveInRow: row andInColumn: col];
	NSString *winner = ( (actualWinner == _X_) ? @"_X_" : (actualWinner == _O_ ? @"_O_" : "NONE") );
	STAssertEquals(expectedWinner, actualWinner,
				   @"Move made in row %d and column %d by player %@ should win but returned winner was %@", row, col, 
				   [game valueInRow:row andInColumn:col] == _X_ ? @"_X_" : @"_O_"winner);
	[winner release];

It’s complaining about a pointer type mismatch in my conditional expression. I think I’m being too clever here using ternary operators instead of breaking out the classic if/esle or switch statements. I’m just trying to print out exactly which player is reported as the winner in my test because I like fully descriptive assertion failure messages but at the same time I like more terse code. I hate breaking out verbose if/else blocks if I can avoid it.

On a side note, none of this will do me any good if I can’t run test suites in an iPhone project. Still I’m thinking that I could probably hack around the limitation somehow by creating a Cocoa library project just to get the core logic unit tested then somehow figuring out how to include that unit tested code in my iPhone project. I’m certain there’s a loophole somewhere and I’ll stumble across it shortly. I still wonder why it has to be such a challenge? C’mon, we’re in like, the 27th century or something like that! There’s no excuse for any moder frameworks to be created sans unit test support. I view this as completely unacceptable!

Titles, Strings, and Threads

I just got bit by a subtle Objective C bug. I’m writing a basic application that starts an asynchronous counter that updates an onscreen label. Common sense would suggest pseudo-code like this:

   if button title = "Start"
      set button title = "Stop"
      set button title = "Start"
end onButtonPress

The problem is this. The UIButton class in Cocoa has a read only currentTitle property. There’s no writing to this property however you can write to setTitleForState and pass a UIControlStateNormal enum. (Why do I hate enums?) So I’m thinking it’s enough to query the currentTitle property and then set the title for the normal state from “Start” to “Stop”, right? Wrong! Somehow the currentTitle property hangs onto the original value and instead I should be querying the titleForState: method instead! Can you tell I’m missing the JDK?

Stringing me along

Did you know that, when using Objective C over Cocoa, there is no trim method! I’m fooling with some really simple code that should take all of 2 minutes tops but because ObjC/Coca breaks things out completely different than Java I’m facing collisions left and right. Luckily I think I’m smart enough to figure out why:
NSString @someString = @”Start”;
@”Start” == someString;
is not a true statement. I’m relying on my Java background which states that == referrs to object identity not equality is you might hope/guess/pray. Now I’m pawing through the String Programming Guide that sends me off on a tangent. I’m looking at the compare method which returns an NSComparisonResultwhich is typdef’ed to some crazy enum with ordering values. I don’t use enums, not even in Java so now I gotta read up on that too? Where is .equals()? Oh wait… I just looked at the string docs again and there is an isEqualTo method… *phew*

It’s going to take some getting used to. I found the quick API lookup in XCode which is mandatory for writing anything more sophisticated than HelloWorld. There’s a lot of other niceties in XCode as well but, BUT I stand by my original word that XCode has nothing on IntelliJ Idea. There’s an idea! Why doesn’t Jetbrains create an iPhone IDE? That would be off the chains!

The Black Art of iPhone Development

Experimenting with some Cocoa Touch stuff over the iPhone SDK, just for kicks. I’m not comfortable, getting there, but not comfortable yet. I truly miss Idea/Java when using XCode/Obj C. Don’t get me wrong, Apple put a lot of nice features in XCode (a very pretty IDE) and Obj C blows away anything C/C++ related. I can’t see how I’d be comfortable using it for daily development. Too many things are left out. For example, where the HELL is local history? Why does refactoring involve a dialog??? I would think that Apple of all people would get this right on the 1st attempt. Die hard programmers love things like EMacs, hot keys, command lines, single command/action type systems. Anything that takes you out of that flow is a distraction.

Here’s the thing, I think XCode is beautiful. I can see Apple put their touch on it as they do everything else. I love the way the matching left bracket animates when you type a right bracket. Hands down the IDE is prettier than anything from Eclipse, Netbeans, or Idea. For mobile development it beats the pants off of the competition. Blackberry might as well call up their chief JDE architect, invite him out for beer, chat about the McCain/Obama campaign for a good twenty-thirty minutes, pretend to have car trouble late in the night when it’s time to go home, then quietly slip a choke-wire around his neck while he’s not looking and squeeze the living RAPC knowledge out of him slowly. If this were a competition on sexiness, XCode would be Jessica Alba, Eclipse would be Tyra Banks (sexy but fading), Idea would be America Ferrera (appealing ot a certain niche), and Net Beans would be Britney Spears (sexy to those who have no idea what sex appeal truly is).

Productivity is key to an IDE. If productivity were money you would be living like Warren Buffet with Idea, paid like Bill Gates with Eclipse, comfortable like Trump with Net Beans, and just making it like Michael Jackson with XCode. (On the surface you look rich but behind the scenes there’s all these issues.) I need to be able to refactor comfortably. I need to be able to depend on local history instead of some just the undo button. I’d like to be able to tag my project, or whatever file I’m working on so that I can introduce changes and roll back and forth to see the impact of those changes. I’d like to be able to shelve my changes when I get side-tracked, then pull them off the shelf later without missing a beat. Productivity! XCode lacks all of these features and these are the things that make development a breeze.

Productivity aside my biggest problem comes from the lack of simplistic code examples and full fledge easy to use documentation available for the iPhone SDK. There are downloadable sample projects but nothing that shows you, fo instance, “Hello world” over an HTTP request. I can’t even pin point conclusive text that explains whether the iPhone UI follows the same single thread event dispatch model as is present in every UI toolkit I’ve encountered. My common sense tells me that all things like network calls should be done on a background thread to free up the EDT but I can’t find a conclusive simple code example that says, “Hey Idiot, call the OperationQueue API to background your slow network call then batch your screen updates back onto the EDT thread using this other API!” Then Apple makes things worse with their non-disclosure act… not allowing those who know disclose what they know so those who don’t know can know, y’know? it’s like a big secret, learning iPhone dev stuff must be done exclusively using the Apple online docs and nothing else. If you know anything about the black art speak up so we can open a private channel. I really want to learn and Apple isn’t making it easy. Holla’ at’cha man…

Apple must hate me, and most of you too

So I’m checking out the iPhone SDK this weekend. But I’m checking it out window shopping style because I can’t actually use or touch any of it. It’s like that JVC car stereo head unit I wanted back when I was 18 with no steady income. I could see it at the store. I could dream about it. I thought it looked really cool. But I couldn’t take it home and have my way with it. The iPhone SDK is just like that. How did we get to this point? How is it that an eager developer such as myself has absolutely no access to a a toolkit that would allow me to create products which help raise the visibility of a major platform owned by the same company that makes the toolkit? It’s all the result of the assumption many engineers have that everyone shares their vision. In other words, because I’m running Windows Vista SP47 everyone else must be as passionate about Windows upgrades and as paranoid about system updates so they should also be running Vista SP47.

Here’s the real problem. I got a Macbook pro, a pretty recent model. The iPhone SDK lists OS X 10.5 as a requirement. I’m running Tiger 10.4. I haven’t upgraded to Leopard. I mean I could, but why should I? My primary development is mostly Java and from what I hear Leopard takes a dump on JDK 5 and higher. I don’t even know if it supports JDK1.4.2. So an upgrade would be counter productive for me. Even if I wasn’t a Java developer, why should I spend how many more dollars for the upgrade? Just to develop for the iPhone? If Apple really wants to entice me to upgrade they should do so with a shiny new JDK release on Leopard. Lastly, I started the download of the iPhone SDK yesterday before I was certain of the system requirements. At 2.1GB my download monitor was reporting 2 1/2 weeks to complete the transfer. (Ok, my router got a little glitched and started affecting my throughput reducing my 1.5 DSL to less than 28.8K dial-up but that’s a whole ‘nuther topic.) I thought the JDK was getting beefy when they stuffed a DBMS and started approaching the 100MB threshold.

In all, yes – I’d like to use the iPhone SDK. I like what I see in the XCode demos. (I wanna see how the latest XCode stuff compares with IntelliJ Idea.) I’m eager to start. There’s just this hurdle in my way and I’m not sure if I’m ready to jump.