zer0gravitas
zer0gravitas

Reputation: 365

How to bind textfields to attributes of one core data entity containing one row?

I have a view that wants to show summarized usage data for my app. Conveniently enough I have a cocoa core data entity with all the usage data pre-aggregated (so it has only one row ever). I would like to bind each individual attribute in the entity to different NSTextFields (eg not in an NSTableView).

This does not seem to be a usage pattern that core data + interface builder handles nicely. So far what I am doing is duplicating my aggregated attributes into NSUserDefaults and binding my text fields to the defaults. I would like an better, elegant way to do this.

Any better ideas out there? Do I need to be smacked in the head with a big fat clue?

Thanks as always for reading...

Upvotes: 2

Views: 1005

Answers (2)

zer0gravitas
zer0gravitas

Reputation: 365

Ok I just hit my own head with my own big fat clue. The solution was to use NSObjectController.

  1. Add instance of NSObjectController to the NSWindowController implementation as an IBOutlet.
  2. Add the NSObjectController to the xib for the dialog and bind the fields to it.
  3. Link the NSObjectController in your view/window controller (File's Owner) to the NSObjectController in the xib.
  4. Implement the controller's windowDidLoad.

In my case it looks like this in the header:

NSObjectController *dataCtrl;
...
@property (nonatomic, retain) IBOutlet NSObjectController *dataCtrl;

And like this in the implementation

    @synthesize dataCtrl;
    ...
    - (void)windowDidLoad
    {
        NSManagedObject *totals = [StatsSupport getTotalRecord];
        [[self dataCtrl] setContent:totals];   // where the rubber meets the road
        [super windowDidLoad];
    }

And of course +[StatsSupport getTotalRecord] is your basic core data fetch type code which if you read this far you know how that looks. (and it will probably already exist since you need this code or something similar just to perform normal data reading/updating)

Lastly do a little happy dance because you made cocoa do some work for you.

Upvotes: 1

Mundi
Mundi

Reputation: 80265

-(void)updateFields {
  // fetch the row from the persistent store into your custom object
  // then get a reference to the data in your object, e.g.
  MyDataObject *data = [resultsArray objectAtIndex:0];

  myTextField1.text = [NSString stringWithFormat:@"%d", [data.anIntegerValue intValue]];
  myTextField2.text = data.aTextValue; 
  // etc...
}

Upvotes: 0

Related Questions