View Full Version : Adding saving to a Document based app

Jun 25, 2007, 06:19 AM
Hey everyone

I was hoping someone here could help me. I'm quite new to both Obj-c and Cocoa and have been trying to teach myself by building a few trivial apps. The latest is a searchable dictionary app, which allows users to add and remove entries. (I want to use it for conlangs)

Anyway the app is a Cocoa document based app and has three classes.

a MyDocument class which inherits from NSDocument
a FilteredArrayController which inherits from NSArrayController. It reimplements the newObject: and adds a search functionailty by reimplementing arrangeObjects:
a Word class which stores a word, it's meaning, etymology and notes.

Now I thought that in order to add saving to the app I had to implement a few methods in the MyDocument class and have custom classes to archive themselves.

So in MyDocument I added this:

- (void)windowControllerDidLoadNib: (NSWindowController *) aController
[super windowControllerDidLoadNib:aController];
- (NSData *)dataRepresentationOfType: (NSString *)aType
return [NSKeyedArchiver archivedDataWithRootObject:words];


- (BOOL)loadDataRepresentation: (NSData *)data ofType: (NSString *)aType
[self setWords:[NSKeyedUnarchiver unarchiveObjectWithData:data]];
return YES;

Where words is an NSMuatableArray. The class also has an IBOutlet to an NSArrayController which is linked to my custom NSArrayController. All the UI elements are bound to this ArrayController.

In my Word class I've added the following:

- (void)encodeWithCoder: (NSCoder *)coder
[coder encodeObject: _word forKey:@"word"];
[coder encodeObject: _meaning forKey:@"meaning"];
[coder encodeObject: _notes forKey:@"notes"];
[coder encodeObject: _etym forKey:@"etym"];
-(id)initWithCoder: (NSCoder*)coder
if (self = [super init])
[self setWord: [coder decodeObjectForKey:@"word"]];
[self setMeaning:[coder decodeObjectForKey:@"meaning"]];
[self setNotes:[coder decodeObjectForKey:@"notes"]];
[self setEtym: [coder decodeObjectForKey:@"eytm"]];

From what I undertsand this should have worked. The app seems to save fine, but When i load up a file the UI elements are not populated. Is this because I need to manually repopulate the ArrayController or is there something really simple I'm missing here.?

Jun 25, 2007, 06:29 AM
Does your Word clas implement the NSCoding protocol?

Jun 25, 2007, 06:50 AM
Does your Word clas implement the NSCoding protocol?

Yes it does

If i understand it correctly all I need to do is this:

@interface word : NSObject <NSCoding>

to implement NSCoding right?

Jun 25, 2007, 02:21 PM
sussed it

I deserve a great big thwak over the head. I forgot to set the content array binding of my array controller. So when my document attempted to archive my words array, it was empty as the array controller hadn't been passing the info back to it.

*slaps forehead* :)