tags:

views:

10

answers:

1

I have creating an address book application . My AddressController.h class is ---

@interface AddressController : NSObject { IBOutlet id nameField; IBOutlet id addressField; IBOutlet id tableView; NSMutableArray *records; } - (IBAction)addRecord:(id)sender; - (IBAction)deleteRecord:(id)sender; - (IBAction)insertRecord:(id)sender;

@end

Implementation class is as follow:-

@implementation AddressController

  • (id)init {
    records = [[NSMutableArray alloc] init]; return self; }

  • (NSDictionary *)createRecord { NSMutableDictionary *record = [[NSMutableDictionary alloc] init]; [record setObject:[nameField stringValue] forKey:@"Name"]; [record setObject:[addressField stringValue] forKey:@"Address"]; [record autorelease]; return record; }

  • (IBAction)addRecord:(id)sender { [records addObject:[self createRecord]]; [tableView reloadData]; }

  • (IBAction)deleteRecord:(id)sender { int status; NSEnumerator *enumerator; NSNumber *index; NSMutableArray *tempArray; id tempObject; if ( [tableView numberOfSelectedRows] == 0 ) return; NSBeep(); status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected record(s)?", @"OK", @"Cancel", nil); if ( status == NSAlertDefaultReturn ) { enumerator = [tableView selectedRowEnumerator]; //enumerator here gets indexes of selected rows tempArray = [NSMutableArray array]; while ( (index = [enumerator nextObject]) ) { tempObject = [records objectAtIndex:[index intValue]]; // we store selected rows in temporary array [tempArray addObject:tempObject]; } [records removeObjectsInArray:tempArray]; // we delete records from 'records' array which are present in temporary array [tableView reloadData];
    } }

  • (IBAction)insertRecord:(id)sender { int index = [tableView selectedRow]; [records insertObject:[self createRecord] atIndex:index]; [tableView reloadData]; }

  • (int)numberOfRowsInTableView:(NSTableView *)aTableView { return [records count]; }

  • (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex { id theRecord, theValue; theRecord = [records objectAtIndex:rowIndex]; theValue = [theRecord objectForKey:[aTableColumn identifier]]; return theValue; }

  • (void)awakeFromNib { [tableView reloadData]; }

@end

I am able to add and delete records to/from address book. But when I start the application again all records are gone. I want to store records somewhere (like in user defaults ) so that when I start the application again existing records are shown in the address book. I am not getting the idea how to do it using user defaults. Please suggest solution.

A: 

Do not use user defaults for this. You may want to explore Core Data. Another option to explore is NSCoding.

NSCoding will have less of a learning curve, fairly simple to implement. Core Data is tougher to grasp, but would be the wiser choice in the long run.

Brad Goss