More and more when I write code, I’m looking for optimizations, short cuts and less typing. This can mean a careful balance between maintainable code and author convenience. Here’s an example of something I use in every program I write.
I use the preprocessor to define debug modes for myself to produce debug output under certain conditions. Here I define DEBUG_ON to produce a boolean value that can be tested throughout my program.
ANSI C Version
#define DEBUG_ON 1 #define DEBUG_F_L if (DEBUG_ON) printf("%s() \t\tLine: %4d\n", __FUNCTION__, __LINE__);
Objective C Version
#define DEBUG_ON 1 #define DEBUG_F_L if (DEBUG_ON) NSLog(@"%s() \t\tLine: %4d\n", __FUNCTION__, __LINE__);
This can save a lot of redundant typing/pasting and reduces code eyestrain.
e.g. This…
static NSString *cellIdentifier = @"accessCell"; DEBUG_F_L Accounts *account = [self.arrAccounts objectAtIndex:indexPath.row]; LocationCollectionViewCell3 *cell = (LocationCollectionViewCell3 *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath]; if (Nil == cell) { DEBUG_F_L cell = [[LocationCollectionViewCell3 alloc] init]; } cell.orgNameLabel.text = account.org_display_name; cell.locationNameLabel.text = account.location_name; cell.locationCityLabel.text = account.location_city; cell.actionQtyLabel.text = @""; [cell.backgroundImage setImageWithURL:[NSURL URLWithString:account.org_login_logo_url]]; DEBUG_F_L
vs. this…
static NSString *cellIdentifier = @"accessCell"; // NSLog(@"%s \t\tline: %d", __FUNCTION__, __LINE__); Accounts *account = [self.arrAccounts objectAtIndex:indexPath.row]; LocationCollectionViewCell3 *cell = (LocationCollectionViewCell3 *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath]; if (Nil == cell) { // NSLog(@"%s \t\tline: %d", __FUNCTION__, __LINE__); cell = [[LocationCollectionViewCell3 alloc] init]; } cell.orgNameLabel.text = account.org_display_name; cell.locationNameLabel.text = account.location_name; cell.locationCityLabel.text = account.location_city; cell.actionQtyLabel.text = @""; [cell.backgroundImage setImageWithURL:[NSURL URLWithString:account.org_login_logo_url]]; // NSLog(@"%s \t\tline: %d", __FUNCTION__, __LINE__);
Discussion
No comments for “C Preprocessor Life Saver(s) – Part 1”