Gold Challenge solution using class method


#1

I found that I could format the date with a lot less code by not creating an instance variable for the NSDateFormatter class, and use its class method localizedStringFromDate:dateStyle:timeStyle: instead, much the same way as we use NSString’s stringWithFormat: (which I also used).

In BNRMapPoint.m:

[code]@synthesize coordinate; // title removed so as to add dates for GOLD CHALLENGE

  • (void)setTitle:(NSString *)t
    // GOLD CHALLENGE: add date set to title of annotation
    {
    NSDate *currentDate = [NSDate date];
    NSString *stringDate = [NSDateFormatter localizedStringFromDate:currentDate
    dateStyle:NSDateFormatterShortStyle
    timeStyle:NSDateFormatterNoStyle];
    title = [NSString stringWithFormat:@"%@ (%@)", [t copy], stringDate];
    }

  • (NSString *)title
    {
    return title;
    }[/code]

Setting the date style to NSDateFormatterShortStyle give it the format “6/2/12”, and setting time style to NSDateFormatterNoStyle effectively lopped the time off. The resulting string now looks like “San Francisco (6/2/12)”.


#2

Thanks Pauley this helped me out


#3

I tried Pauley’s solution, but placed the code in the designated initializer instead:

[code]// Designated initializer

  • (id)initWithCoordinate:(CLLocationCoordinate2D)c
    title:(NSString *)t
    {
    self = [super init];
    if (self) {
    coordinate = c;

      // Use today's date for appended text
      NSDate *today = [NSDate date];
      
      // Format the date to short style with no time stamp
      NSString *stringDate = [NSDateFormatter localizedStringFromDate:today
                                                            dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterNoStyle];
      
      // Set a string to use the supplied text and append the date
      NSString *td = [NSString stringWithFormat:@"%@ %@", t, stringDate];
      
      // Set the title with the modified text
      [self setTitle:td];
    

    }
    return self;
    }[/code]