A better way to work with NSDate

Working with NSDates and calendrical calculations can sometimes be a pain. Adding days, subtracting months, and adjusting today’s date to midnight. It may be tempting to resort to the following solution:

By applying a “Normalize” category (you can call your whatever you like) on NSDate, it is now possible to apply date adjustments directly to the date you’re working with. Keep in mind that in the example above we reference sharedCalendar. This sharedCalendar is an instance of NSCalendar and is best obtained from a single resource (eg. AppDelegate property, Singleton object, etc.). Doing so significantly reduces overhead of these methods when called inside a loop (you don’t want to be creating an instance of NSCalendar for every iteration of the loop, as that can be quite expensive).

In fact, here’s a possible implementation of an NSCalendar category using the singleton design pattern. Include this in your NSDate+Normalize category header file, and you’ll have access to a shared calendar wherever you include this category on NSDate.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

@interfaceNSCalendar(Shared)

+(instancetype)sharedCalendar;

@end

@implementationNSCalendar(Shared)

+(instancetype)sharedCalendar{

staticNSCalendar*_sharedCalendar;

staticdispatch_once_t onceToken;

dispatch_once(&onceToken,^{

_sharedCalendar=[selfcurrentCalendar];

});

return_sharedCalendar;

}

@end

That more or less sums up some of the better ways to work with NSDate and NSCalendar for calendrical calculations and the like. As always, feel free to use the code in your personal and commercial projects.