Challenge: Using Block with NSNotification Center (SOLUTION)

Challenge: In Chapter 27, you used NSNotificationCenter’s addObserver:selector:name:object: method to register to receive callbacks via your zoneChange: method. Update that exercise to use the addObserverForName:object:queue:usingBlock: method instead.

JSLogger.h

[code]@property (nonatomic) NSDate *lastTime; // a property that holds a date

  • (NSString *)lastTimeString; // a method that returns the date as a string
  • (void)updateLastTime:(NSTimer *)time; // an action-method to be triggered by the timer[/code]

JSLogger.m

[code]- (NSString *)lastTimeString
{
static NSDateFormatter *dateFormatter = nil; // static because one object for all calls
if (!dateFormatter) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@“MMM dd, yyyy (h:mm.s a)”];
NSLog(@“Date has been formatted.\n”);
}
return [dateFormatter stringFromDate:self.lastTime];
}

  • (void)updateLastTime:(NSTimer *)time
    {
    NSDate *currentDate = [NSDate date];
    [self setLastTime:currentDate];
    NSLog(@“Current Time: %@\n”, self.lastTimeString);
    }[/code]

Main.m

[code]JSLogger *logger = [[JSLogger alloc] init];

[[NSNotificationCenter defaultCenter] addObserverForName:NSSystemTimeZoneDidChangeNotification
object:nil
queue:nil
usingBlock:^(NSNotification *notification) {
NSLog(@“Time Zone changed to “%@”.\n”, [NSTimeZone systemTimeZone]);
}];

__unused NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0
target:logger
selector:@selector(updateLastTime:)
userInfo:nil
repeats:YES];

[[NSRunLoop currentRunLoop] run];[/code]

Output:

[quote]Date has been formatted.
Current Time: Jun 26, 2015 (9:10.23 AM)
Current Time: Jun 26, 2015 (9:10.25 AM)
Current Time: Jun 26, 2015 (9:10.27 AM)
Time Zone changed to “Africa/Algiers (GMT+1) offset 3600”.
Current Time: Jun 26, 2015 (2:10.29 PM)
Current Time: Jun 26, 2015 (2:10.31 PM)
Time Zone changed to “America/Campo_Grande (GMT-4) offset -14400”.
Current Time: Jun 26, 2015 (9:10.33 AM)
Current Time: Jun 26, 2015 (9:10.35 AM)
Time Zone changed to “America/New_York (EDT) offset -14400 (Daylight)”.
Current Time: Jun 26, 2015 (9:10.37 AM)[/quote]