I have seen solutions posted that clutter either the initWithCoordinate:title: method of MapPoint or even the AppDelegate. I came up with a solution that puts the date formatting logic into a custom setSubtitle accessor method, which seems appropriate, since only the subtitle needs to know about the fact that the subtitle has a formatted date. This is an easy, clean solution, because aside from the custom setSubtitle method, only 4 lines of code need to be added to the code from the book.
First, I’ll give the four new lines of code that are added:
In MapPoint.h, declare an NSString *subtitle, just after (and just like was done for) *title.
Also add the @property for subtitle. But make it readonly, because we don’t want the compiler to generate a setSubtitle method; we’re going to write a custom one. Here’s the @property statement:
@property (nonatomic, copy, readonly) NSString *subtitle;
- In MapPoint.m, we’re going to generate a subtitle whenever we generate a title, but we’re not going to supply a value (since it will be set automatically to the current date/time). So after the setTitle call add this:
[self setTitle:t]; //from book
[self setSubtitle]; //add this line
- Add to dealloc:
Don’t forget to add subtitle to your @synthesize statement(s). Remember it will direct the compiler to write the “get” accessor method for subtitle, but not the “set” method since it’s readonly. Now we’ll write setSubtitle, which has the date formatting logic. Add the following method to MapPoint.m:
NSDate *now = [[NSDate alloc] init];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
NSString *stringNow = [df stringFromDate:now];
subtitle = stringNow;
That’s it! I welcome any comments on this (and other) solutions.