Search code examples
iosobjective-cnscalendar

NSCalendar - set own firstWeekday globally


Is there possibilty to set custom firstWeekday? Should i subclass NSCalendar ?

For now i have to set it like this in every place where i need to use NSCalendar

NSCalendar* calendar = [NSCalendar currentCalendar];
calendar.firstWeekday = [NSUserDefaultsHelper firstDayOfWeek];

Solution

  • You could write a category of NSCalendar with a lazy instantiated variable:

    @interface NSCalendar (WeekdayCalendar)
    
    + (NSCalendar *)customWeekdayCalendar;
    
    @end
    
    @implementation NSCalendar (WeekdayCalendar)
    
    + (NSCalendar *)customWeekdayCalendar
    {
        static NSCalendar *customCalendar = nil;
        if (customCalendar == nil) {
            customCalendar = [self currentCalendar];
            customCalendar.firstWeekday = [NSUserDefaultsHelper firstDayOfWeek];
        }
        return customCalendar;
    }
    
    @end
    

    Then you can use calendar from everywhere

    NSCalendar *myCalendar = [NSCalendar customWeekdayCalendar];