In a typical iOS application, where should one put application wide objects? I’d like to centralized my Date formatting code and I would be interested in hearing suggestions on best practices for doing so.
For example, I have the following code to do date formatting:
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSString *usFormatString = [NSDateFormatter dateFormatFromTemplate:@"EEE, MMM d YYY" options:0 locale:usLocale];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = usFormatString;
((UILabel *)[selectedCell.contentView viewWithTag:1]).text = [formatter stringFromDate:date];
I’d like to keep the formatting code as DRY as possible.
EDIT: This turned out to be a multipart answer and I took the approach of using a combination of a Singleton and creating a Category for NSString. I upvoted most of you, but I accepted @Jack_Lawrence.
I like using Objective-C categories for that sort of stuff. Categories are good for extending the abilities of existing objects, especially objects from frameworks that you don’t have control over. Make sure to prefix method names so you don’t conflict with current/future methods Apple may implement.
In this specific case, I would create a category on NSDate called NSDate+DateFormatting and implement a method that returns an NSString from the date receiver: