Article:
  The Cocoa Controller Layer
Subject:   Override add?
Date:   2004-07-05 14:19:11
From:   markstone1
Response to: Override add?

I just worked out a pretty easy way to set the title/author of newly created books. Hope it helps:


First, subclass NSArrayController in Interface Builder. Nmae it something like MyController. Also, create the files for the new class in your project.
Next, select the BookController instance that was created before and change its 'custom class' to MyController.
Go back to Xcode. Add the following line to MyController.h (it doesn't really matter, but I got a compiler warning otherwise):
#include "Book.h"
Now, override the -(id)newObject: method in MyController.m as follows:


- (id)newObject
{
id newBook = [super newObject];
[newBook setTitle: @"Unknown Title"];
[newBook setAuthor: @"Unknown Author"];
return newBook;
}


Just drag MyController.h into IB, save everything and compile!

Full Threads Newest First

Showing messages 1 through 1 of 1.

  • Override add?
    2004-08-01 00:32:42  donarb [View]

    Creating a special subclass just to set an object's attributes is way too much work. You'd be better off just putting the code that assigns the default names into the Book class itself, using the init() method. Somewhere down the road you'll be banging your head against the wall trying to figure out where the default name is being set. Put this into the Book object instead:


    - (id)init
    {
    self = [super init];
    if (self != nil) {
    [self setTitle:@"Unknown Title"];
    [self setAuthor:@"Unknown Author"];
    }
    return self;
    }