Chp 6 Challenge 2 Solution

Monday, November 14, 2005

So the solution to this challenge involves a lot of editing within the MyDocument.nib file, but first we'll set up a new project so we won't ruin the one that uses the NSArrayController.

1. Create New Cocoa Document Based Project
2. Add the Person.h and Person.m from earlier in the chapter to the project.
3. Use the code shown for the MyDocument class.
4. Open the MyDocument.nib.
5. Layout the NSTableView and the two buttons just as you did in the earlier project. Make sure to set up the formatter on the second column.
6. Select the first NSTableColumn of the table. Set its identifier attribute to "personName".
7. Select the second NSTableColumn of the table. Set its identifier attribute to "expectedRaise".
8. Go back to the XCode project and drag the MyDocument.h file to the nib window to update the MyDocument class.
9. Now connect the FileOwner (aka the MyDocument instance) to the NSTableView and make it the tableView outlet.
10. Connect the Create New button to the FileOwner's createEmployee action.
11. Connect the Delete button to the File Owner's deleteSelectedEmployees action.
12. Connect the NSTableView to the File Owner and select the NSTableView's dataSource delegate.

That's enough to build and run the application to seed employees into the table.


To add sorting you need to add the following method to the MyDocument.m file....


- (void)tableView:(NSTableView *)aTableView
sortDescriptorsDidChange:(NSArray *)oldDescriptors {
NSArray *newDescriptors = [aTableView sortDescriptors];
[employees sortUsingDescriptors:newDescriptors];
[aTableView reloadData];
}


Once you've added that method go back to the MyDocument.nib file do the following steps...
1. Select the first NSTableColumn and make the sortKey "personName", and the selector "caseInsensitiveCompare:"
2. Select the second NSTableColumn and make the sort "expectedRaise", and leave the selector as "compare:"
3. Connect the NSTableView to the File Owner object and make the File Owner the delegate object for the NSTableView

Build and run to see the sorting work.

Click here to download a working version of the project. This project was created using XCode 2.2 and will not immediately work with previous versions of XCode.

Comments: Post a Comment


<< Home

This page is powered by Blogger. Isn't yours?