Search code examples
cocoacore-datansarraycontroller

Why is my newObject method not called?


I am following an exercise from Aaron Hillegass's Cocoa book - chapter about Core Data. I have a document-based application that saves car(s) data into an array controller, it then uses bindings... The problem is that I have a date picker, and I want to initialize it to today's date as soon as a new car is added, so we're subclassing NSArrayController's newObject method. But, it always shows 2/12/1982! The NSLog inside the newObject method is not called. What am I (or book) missing?

CarArrayController.h

#import <Foundation/Foundation.h>

@interface CarArrayController : NSArrayController

@end

CarArrayController.m

#import "CarArrayController.h"

@implementation CarArrayController

- (id)init  //this is not called!
{
    self = [super init];
    if (self) {
        NSLog(@"in init");
    }
    return self;
}

-(id)newObject {   // not called either
    id newObj = [super newObject];
    NSDate *now = [NSDate date];
    [newObj setValue:now forKey:@"datePurchased"];
    NSLog(@"yep");
    return newObj;
}

@end

MyDocument.xib

Has an instance of NSArrayController, its Custom Class name is set to CarArrayController.

PS: For my Array Controller in MYDocument.xib, "Prepares Content" button is checked, so automaticallyPreparesContent should be set to YES...?


Solution

  • I think there is a bug in Xcode 4.2, there is a thread on that in bignerdranch's forum: http://forums.bignerdranch.com/viewtopic.php?f=183&t=3465

    Somehow Xcode doesn't realize that I changed the Array Controller to my custom class. To get it to work, I first added the initWithcoder method, then archived the application, then went back and deleted the initWithCoder method (going back to my original code), and now it works! People in the thread above propose other solutions that don't make sense… I'll assume it's a bug…