The World’s Leading Microsoft .NET Magazine
   
 
The .NET Addict's Blog

My Top Tags

                                                           

My RSS Feeds








I heart FeedBurner

Latest Diggs - Programming

Computers Blogs - Blog Top Sites

Site Hits

Total: 3,824,063
since: 19 Jan 2005

A NYC .NET Developer in Steve Jobs' Court - Day 1

posted Wed 31 Jan 07
I originally thought that I would be postponing my first blog post about Cocoa programming on the Mac for .NET developers until after Leopard came out. However, since I've had trouble downloading Leopard myself, I couldn't resist the temptation and I started writing some code in Xcode on Mac OS X Tiger. 

Disclaimer: I am not intending to prove that Cocoa programming is better or worse than .NET Programming. I am merely exploring alternative means of development and journaling my progress with respect to a very .NET-heavy audience.

I've had 13 years of professional programming experience, and I've had another 10 years of hobbyist development experience before that. So, needless to say, I figured I could jump into Xcode and be rollin' in no time. Unfortunately this is where the men are separated from the boys, because Xcode and Interface Builder are actually easier to use for people who have not had any exposure to Visual Studio. Some Apple folks refer to people without Visual Studio experience as "untainted". Anyway, I ran into a stumbling block early on that I'm sure a lot of died-in-the-wool Microsofties will run into.

I tried to create the stereotypical "Hello World" application. I dragged a button onto a form and then I figured, "What the hell, this ought to work", so I double-clicked the button and was ready to try and figure out how to get a message box to come up. Much to my chagrin, all I did was pull up the properties inspector for the button. 

My first reaction was to drop Xcode and go back to Visual Studio where I felt comfortable. You know how, even though something might actually smell really, really bad, the fact that you're familiar with it and might even call it home makes it endearing? The same is true of a development tool. Regardless of whether your tool is good or bad, the fact that its the tool you've been using for years makes it feel comfortable and familiar, like a security blanket.

I took a step back and tried to figure out what the hell was going on. After a few minutes, I realized that Xcode was actually doing a really, really, really good thing. The vast majority of problems that arise from a poor separation of concerns between the GUI and the underlying code, model, and controller (if you even have such constructs in your app!) stem from the fact that you can double-click a button and immediately start writing code without thinking about the consequences of such a thing.

The NIB (stands for NeXTStep Interface Builder) file is a loosely coupled, standalone, user interface definition. It wouldn't make sense to double-click a button and immediately be taken to a code-behind. Instead, you have to create a controller class, and then ctrl-drag from the button to the controller and then pick the outlet you're going to use (something like click: or calculate:). To me, as a huge fan of the MVC pattern, this makes perfect sense. And it seems so elegant in its simplicity, and so incredibly cool in the fact that it is truly enforcing good design simply by the way the IDE works.

So to get a handle on how Xcode wants me to implement the MVC pattern, I created a new application called Currency Converter, which is one of the samples in the Apple developer documentation that includes a full walkthrough tutorial (awesome tutorial, by the way!). Here's a screenshot of the GUI that I created:


There is a model class called Converter that contains the data underneath the form. There is a controller responsible for maintaining the interaction with the user that is contained within a class called ConverterController, and finally there is the view that is wrapped up neatly inside the NIB file.

Here's the code for the model object (Converter):

#import "Converter.h"

 

@implementation Converter

 

- (float)convertCurrency:(float)currency atRate:(float)rate {

return currency * rate;

}

@end



And here's the code in the controller (ConverterController):

#import "ConverterController.h"

 

@implementation ConverterController

 

- (IBAction)convert:(id)sender

{

float rate, currency, amount;

currency = [dollarField floatValue];

rate = [rateField floatValue];

amount = [converter convertCurrency:currency atRate:rate];

[amountField setFloatValue:amount];

[rateField selectText:self];

}

 

@end


What the controller's convert: method (I think they call it something other than a method in Cocoa) is doing is reading the currency and rate fields by sending the floatValue message to the dollarField and rateField outlets (created visually in Interface Builder) to get the current value from the text boxes. Next, the amount is set to the value of the convertCurrency:atRate method. Finally, the amountField text box is given the float value that is the result of the operation, and the ratefield gets focus after the operation.

This is pretty much the most basic example of functionality that you can get in a Cocoa application. For me, it was pretty eye-opening. I am used to right-clicking my Visual Studio 200x project and adding elements to the project. Its fast, its easy, and it keeps everything in a single, easy-to-find location. Here's the rub - keeping things in a single location like VS 200x does might not be the best thing. From my years of experience with VS, I almost always create project sub-folders, and I go way out of my way to enforce separation of concerns and try and create a M-V-C pattern even in situations where .NET does not appreciate that pattern very much (e.g. ASP.NET applications).

I'm hoping that the next application I post about will be more complex than the SDK sample I posted about here. The point I want to make here is that if you are a .NET developer with good discipline and respect for patterns like MVC, then you will find the transition to Objective-C and Cocoa easier than if you have fallen into the "VB" (no offfense) trap of storing all your code and business logic behind button clicks and other interface elements - creating a tightly coupled mass of spaghetti code.


tags:          

links: digg this    del.icio.us    technorati    reddit

AddThis Social Bookmark Button




1. John C. Randolph left...
Wed 31 Jan 07 9:15 pm

Kevin,

If you want to get your head around Cocoa as quickly as possible, I would strongly recommend picking up Aaron Hilegass's book.

-jcr


2. Craig left...
Wed 31 Jan 07 9:17 pm

I know how you love the MVC pattern but used correctly asp.net is a form of implementation since the code behind can be considered your controller with a dataset, especially strongly typed, - a nice model. It "can" be abused :) but most things can.


3. Craig left...
Wed 31 Jan 07 9:17 pm

by the way - what did you think of your Mac?


4. Kevin Hoffman left...
Wed 31 Jan 07 9:25 pm

Craig - you are right.. If you try hard enough, you can use the .aspx file as the view, the .cs file as the controller, and a model stored somewhere else. However, it is difficult to make this separation clean. So you're right, it is possible, but Visual Studio likes to hide that possibility from you :)

And please don't suggest that a DataSet is a model object. Ew :)


5. Peter left...
Thu 01 Feb 07 4:47 am

If someone is looking for a good intro book on Objective-C without any kind of GUI programming topics involved, I can recommend "Programming in Objective-C" by Steve Kochan, http://www.kochan-wood.com/objc/objc.html. Similarly, a good series of Objective-C intro articles can be found at http://www.macresearch.org/cocoa_for_scientists. Just my two cents.


6. Kevin Hoffman left...
Thu 01 Feb 07 7:30 am

Amazon.com is selling both the Hilegass book and the Kochan book as a "buy both for cheap" deal. Think the two of them together than just over $50, which is fine because my purple SAMS "Cocoa Programming" book ran me $54.


7. Chad Schlesinger left...
Thu 01 Feb 07 7:54 am

A free e-book to learn Objective-C with Xcode is "Become an Xcoder" (http://www.cocoalab.com/cocoalab/developer.php).


8. Chris left...
Thu 01 Feb 07 3:44 pm

Another sample code from Apple worth a look is "Building a Text Editor in 15 Minutes". http://developer.apple.com/documentation/Cocoa/Conceptual/TextArchitecture/ index.html


9. Carli left...
Thu 01 Feb 07 5:53 pm

And don't forget to play with F-Script if you want to feel another "Wow" about the power of Cocoa and Objective-C. It's awesome.


10. l0ne left...
Tue 06 Feb 07 5:55 am

In Objective-C, methods can also be called "messages" (which is why often the 'self' object is called the "receiver"), because they can be sent immediatly just like a method call or they can be stored and sent later (see the docs on the SEL, IMP and NSInvocation types). Think Reflection, but faster.

This opens the door to a lot of nifty tricks, such as bindings or NSUndoManager (try it!).


11. Erik M. Buck left...
Tue 06 Feb 07 10:56 pm

Objective-C methods are called "methods." C++ methods are often called "virtual member functions." Perhaps that is where your confusion originates ?

It is good to start learning a tool set with the ultra-basic samples. That is why "Hello World" and "Currency Converter" exist. However, rest assured that there are are lot more features left to be discovered. I recommend that you build up your conceptual foundations before attempting some of the higher level frameworks / abstractions. If you are like me, you'll want to know how stuff works under the surface.

Cocoa does emphasize the M-V-C separation! Cocoa also provides appropriate frameworks and automation for each layer. You are discovering the View layer with Interface Builder. The Controller layer is greatly simplified by Key Value Coding, Key Value Observing, various "Controller" classes, and Bindings. Many types of persistent Model can be expressed using Core Data.


12. Todd left...
Thu 15 Feb 07 8:26 pm

I'm also a seasoned developer fussing my way thru ObjectiveC and Xcode. I would agree with your perspective about being comfortable with VS.NET and trying to give Xcode a fair shake. However, I'm finding it very difficult.

My software development has focused a lot on creating my on UI controls where I ---dynamically-- create panels, boxes, buttons, etc on the fly. The the --hard-- seperation of the .nib and source code...well let's just say I have not see a way to do that yet. This is where I holding out a ton of hope for Core Animation and Xcode 3.0. I have not see Leopard at all, but I am imagining that Core Animation is Apple answer to Vista's WPF...but on raging steriods. My hope is that the Core Animation will allow me to do quickly create custome User Controls with little pain.

After struggling with Xcode and all the flippin' crazy keyboard bindings and windows burbing and snorting everywhere. I quickly came to realize all those small touches that the VS.NET developers created...make my software developer crazy productive. Case in point --- the collapsable panels --- This is where the user clicks the post-pin and the panel collapses to a tiney window off to the side. Actually, this is a hugh feature that I wish where in iPhoto...I don't need to see the photo library tree 100% of the time.


13. l0ne left...
Fri 16 Feb 07 6:00 am

Todd,

You can add a generated control to a panel exactly the same way you do in .NET -- you create an object of the appropriate class and then add it to its container. .nibs are like Windows Forms-designed forms -- you don't have to use them if you don't need to. (They could be more accurately compared to XAML, though.)


Tag Related Posts

Upgrading your Leopard install to Java SE 6 64-Bit

Mon 12 Jan 09 1:38 P GMT-05
tags:            

Apple drops the iPhone NDA for Released Software

Wed 01 Oct 08 3:54 P GMT-05
tags:          

Cappuccino, Objective-J, and You

Wed 10 Sep 08 6:14 P GMT-05

So I'm in the LA Times ;)

Wed 27 Aug 08 2:51 P GMT-05
tags:                  

MobileMe vs. Live Mesh Throwdown - Round 1

Wed 16 Jul 08 10:33 A GMT-05

Building Model Classes in C# and Cocoa

Sun 15 Jun 08 3:13 P GMT-05
tags:            

MobileMe vs. Live Mesh - Round 1

Wed 11 Jun 08 12:20 A GMT-05

NYC SharePoint Developer Needed

Mon 12 May 08 12:09 P GMT-05

My Macbook Air is masculine, dammit!

Mon 17 Mar 08 6:59 P GMT-05
tags:          

My Macbook Air Review

Sun 02 Mar 08 4:20 P GMT-05

Video of the Macbook Air in Action

Wed 20 Feb 08 3:04 P GMT-05

Leopard Code Sample : Sprinkling in some Bonjour

Tue 27 Nov 07 2:32 P GMT-05
tags:        

Leopard Sample: A Bound NSCollectionView

Mon 29 Oct 07 1:41 A GMT-05

Leopard is out - let the code samples begin!

Fri 26 Oct 07 10:09 A GMT-05
tags:          

My life is complete : iPhone SDK is CONFIRMED.

Wed 17 Oct 07 6:38 P GMT-05
tags:          

Leopard Shipping October 26th!!

Tue 16 Oct 07 4:59 P GMT-05
tags:        

My iPhone Review

Mon 23 Jul 07 1:09 P GMT-05
tags:        

Microsoft Codename Acropolis - Unwrapped

Wed 20 Jun 07 3:22 P GMT-05
tags:              

The dreaded language bleed-over has begun

Tue 19 Jun 07 6:23 P GMT-05
tags:        

Exploring the Delegate Design Pattern

Mon 14 May 07 6:30 P GMT-05

Core Data - Almost too Easy?

Wed 18 Apr 07 2:23 P GMT-05

Will Silverlight be DOA?

Mon 16 Apr 07 8:02 P GMT-05

Exploring the MVC Pattern in WPF

Tue 10 Apr 07 12:51 P GMT-05
tags:                      

My Little Pony .NET Unleashed 2007

Fri 30 Mar 07 1:59 P GMT-05

An experience with the Leopard beta

Mon 26 Mar 07 7:45 P GMT-05
tags: