The Beauty of Cocoa

(Highly geeky post ahead. You’ve been warned!)

I have found the very message that summarizes the beauty of Cocoa in a single word; see by yourselves, hereunder in line 47:

#import <Foundation/Foundation.h>

// The interface of a person
@interface Person : NSObject {
    NSString* firstName;
    NSString* lastName;
    int age;

// The implementation of the Person
@implementation Person
-(id)init {
    if (self = [super init]) {
        firstName = @"";
        lastName = @"";
        age = 0;
    return self;

-(void)dealloc {
    [firstName release];
    [lastName release];
    [super dealloc];

-(NSString*)description {
    return [[NSString alloc]
            initWithFormat:@"Name: %@ %@, %d years old",
            firstName, lastName, age];

// Some code using the Person class
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSMutableDictionary* dict = [[[NSMutableDictionary alloc] init] autorelease];
    [dict setObject:@"Teto" forKey:@"firstName"];
    [dict setObject:@"Rodriguez" forKey:@"lastName"];
    [dict setObject:[[NSNumber alloc] initWithInt:34] forKey:@"age"];

    Person* person = [[[Person alloc] init] autorelease];

    // The beauty of Cocoa can be resumed to this very line:
    [person setValuesForKeysWithDictionary:dict];

    // Now sit back and relax:
    NSLog([person description]);

    [pool drain];
    return 0;