A few inconsistencies in approach…

As I read through some of the code I’ve written I notice things I’ve done twice, unnecessarily. For example a custom table cell has a property (variable/object in normal language) called category of type Category. The table view controller to which it belongs has a routine called configureCell to update the data in it’s cell. It looks something like:

- (void)configureCell:(CategoryTableCell_iPhone *)cell atIndexPath:(NSIndexPath *)indexPath {
    NSManagedObject *mO = [self.fetchedResultsController objectAtIndexPath:indexPath];
	cell.category = (Category *)mO;
	[cell.name setText:[mO valueForKey:@"name"]];
	[cell.desc setText:[mO valueForKey:@"desc"]];
	[cell.icon setImage:[mO valueForKey:@"icon"]];
	[cell setNeedsDisplay];
}

Which is great, the cell itself holds a copy of the Category object and the configureCell method updates the fields and informs the table that it should refresh. Except…. I’m duplicating work. Inside the custom table cell code is this:

- (void)setCategory:(Category *)newCategory {
	if(category != newCategory)
	{
		[category release];
		category = newCategory;
		UIFont *cat = [UIFont fontWithName:@"Georgia" size:18];
		name.font = cat;
		desc.font = cat;
		name.text = category.name;
		desc.text = category.desc;
		[icon setImage:newCategory.icon];
	}
}

Which isn’t obviously called anywhere…. except when you declare a variable or object in objective-c you define getters and setters for it. This is normally done automagically with, at various points:

@property (nonatomic,retain) Category *category;
@synthesize category;

The synthesize bit is key. Of course what synthesize does is define two routines called getCategory and setCategory. By defining our own above we have overridden the default behaviour. Thus the bulk of my code in configureCell is redundant and should just read:

- (void)configureCell:(CategoryTableCell_iPhone *)cell atIndexPath:(NSIndexPath *)indexPath {
    NSManagedObject *mO = [self.fetchedResultsController objectAtIndexPath:indexPath];
	cell.category = (Category *)mO;
	[cell setNeedsDisplay];
}

It seems that depending on the book I have been reading depends on which methods are used or indeed whether both are implemented. You could do away with the custom setter method and implement it all in configure cell. Choose one way or the other, not both. 🙂 Harmless to be sure but inefficient.

This entry was posted in Programming and tagged . Bookmark the permalink.

2 Responses to A few inconsistencies in approach…

Comments are closed.