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,825,585
since: 19 Jan 2005

Building Model Classes in C# and Cocoa

posted Sun 15 Jun 08

As you know, a model object is a simple object that represents state. It is really not much more than a container for data. Business logic often gets stuffed into model objects to make sure that you cannot store an invalid state on that object, but by and large we're looking at property buckets. 

When building a model object in C# that is going to be bound to a UI, typically we do the following things: 

  1. Create a private member variable
  2. Create a public property accessor for that member variable
  3. Implement INotifyPropertyChanging and INotifyPropertyChanged so that bound UI--and potentially dependency-linked model objects--can respond to the changes accordingly by re-rendering or triggering a validation chain.
So what does that look like in C#? A little like this:
 
public class Customer : ModelObject
{
    private int age;
    private string firstName;
    private string lastName;

    public int Age
    {
        get
        {
            return age;
        }

        set
        {
           NotifyPropertyChanging("Age");
           age = value;
           NotifyPropertyChanged("Age");
        }
    }    
    // Implementations of properties for firstname and lastname
 
Where the ModelObject class is just an abstract base class that implements the methods NotifyPropertyChanging and NotifyPropertyChanged, which just fire the corresponding events to let bound GUI and dependent objects know about pertinent changes related to that property. The implementations for the other properties look very similar. People often use frameworks like Spring to take some of the busywork out of building these classes. Also note the naming and casing conventions. Properties and private member variables are nouns. The private members are camel cased with the first letter lower and the public properties are upper init camel cased. This conforms to most agreed-upon design guidelines for class and framework building in C#.  

So what does this look like if you're trying to build a model object that will be bound to UI within Cocoa? Thankfully, it's actually a little simpler. Key-Value-Observing is something that is built right into everything from the ground up, so when you synthesize properties you don't actually have to manually let other objects know about when properties are changing and when they've finished changing - that's all automatic. Here's what the same class looks like in Cocoa:

(Customer.h):

#import <Cocoa/Cocoa.h>

 

@interface Customer : NSObject {

@private

NSString *_firstName;

NSString *_lastName;

NSInteger _age;

}

 

@property (nonatomic, retain) NSString *firstName;

@property (nonatomic, retain) NSString *lastName;

@property (nonatomic, assign) NSInteger age;

 

@end 

(Customer.m):

#import "Customer.h"

 

@implementation Customer

 

@synthesize firstName = _firstName;

@synthesize lastName = _lastName;

@synthesize age = _age;

 

@end 

There's a couple of things that .NET developers need to watch out for when looking at Cocoa documentation. One is that there are a LOT of websites out there that have REALLY OLD code samples. Do not let yourself get lured into not taking full advantage of Objective-C 2.0 unless you plan on building for Tiger or earlier. First you'll see the @private directive. This should make perfect sense - the items declared below this directive are, as should be obvious, private. This is not what a lot of old Cocoa documentation would lead you to believe. Do not believe people when they tell you that all Objective-C member variables are public. That's old school crap and, as a C# programmer, you are more likely to feel comfortable having a very clear separation between your private member variables and your public properties.

What you see next are the @synthesize statements. These will actually build the get/set accessors for you. They are somewhat similar to C# 3.5's automatic property syntax, but not quite. The difference? C# 3.5's automatic properties won't fire INotifyPropertyChanged or INotifyPropertyChanging events for you, but Objective-C synthesized member accessors are KVO-compliant and will notify the GUI when relevant changes occur, automatically.

Anyway, I thought some of you .NET developers looking into Cocoa for whatever *iPhone* reason *iPhone* might find this little comparison useful.

Look for more blog posts along a similar vein that will hopefully start bridging the gap between the .NET and Cocoa worlds and make the transition smooth and easy. 

tags:            

links: digg this    del.icio.us    technorati    reddit

AddThis Social Bookmark Button




1. Rob left...
Sun 15 Jun 08 4:26 pm :: http://www.bluespire.com/blogs

Kevin, Can you recommend a really good book for a proficient C# developer who wants to break into Cocoa?


2. Kevin Hoffman left...
Sun 15 Jun 08 4:41 pm

As always, I would say the single best introduction to Cocoa/Objective-C programming book is Aaron Hillegass' book: Cocoa Programming for Mac OS X.. Just make sure you get the third edition, which now includes coverage of garbage collection and Core Data.


3. Erik Buck left...
Sun 15 Jun 08 7:57 pm

Small critique: I can't recall anyone ever recommending that all or even any Objective-C instance variables should be public. My use of Objective-C goes back 20 years. Many Objective-C programmers will recommend using the default @protected access control for instance variables.

I do enjoy this series of blog posts.


4. Chris Campbell left...
Sun 15 Jun 08 9:50 pm

I suggest that you use the "copy" attribute instead of "retain" when declaring NSString properties. A -copy message works just like a -retain on an immutable NSString, but it will actually make a copy of an NSMutableString, which is typically what you want. You don't want to store a pointer to an object whose contents could be changing behind your back.


5. Kevin Hoffman left...
Mon 16 Jun 08 5:08 am

Right... Retain was a typo, good catch.


6. Jens K. left...
Tue 17 Jun 08 5:31 pm

As a beginner I got a small question: Why is NSString a pointer, but NSString not?


7. Martin Pilkington left...
Fri 20 Jun 08 11:37 am :: http://www.mcubedsw.com

@Jens K: NSString is an object, but NSInteger is just a regular data type. It was introduced to use instead of a regular int so that you can write 32 and 64 bit compliant code.


Tag Related Posts

Upgrading your Leopard install to Java SE 6 64-Bit

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

Smart, Deep Property Notifications in CLINQ v2.0

Tue 07 Oct 08 1:15 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

CLINQ v1.1.0.0 Released!

Fri 02 May 08 5:38 P GMT-05
tags:          

My Macbook Air is masculine, dammit!

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

iPhone Underrated as a Gaming Device?

Fri 14 Mar 08 1:50 P GMT-05
tags:        

My take on the iPhone SDK

Sat 08 Mar 08 1:39 P GMT-05

Jobs says "not likely" to Flash on the iPhone

Thu 06 Mar 08 1:39 A GMT-05
tags:          

My Macbook Air Review

Sun 02 Mar 08 4:20 P GMT-05

iPhone Roadmap March 6th

Fri 29 Feb 08 10:41 P GMT-05
tags:        

Video of the Macbook Air in Action

Wed 20 Feb 08 3:04 P GMT-05

Macbook Airはきれいですよ!

Sun 17 Feb 08 2:38 A GMT-05

Why is O'Reilly Condoning iPhone Hacking?

Mon 11 Feb 08 3:55 P GMT-05

Evaluating my next laptop purchase

Wed 06 Feb 08 8:40 P GMT-05

The iPhone SDK key has been leaked! Oh Noez!!!1

Tue 29 Jan 08 11:36 A GMT-05
tags:        

Why Geeks just don't "get" the Macbook Air

Thu 17 Jan 08 2:30 P GMT-05

Popcorn + TiVo + Macbook Pro + iPhone == Hell Yeah!

Tue 15 Jan 08 3:11 P GMT-05
tags:          

How my ADC membership changed my life

Mon 31 Dec 07 3:57 P GMT-05
tags:      

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: