I have started Xcode 4.1 on my OS X 10.6 partition and tried to compile your code against the iOS 4.3 SDK. It turned out that NSWeekOfYearCalendarUnit
is undefined, so that must have been introduced in later iOS versions. This might explain why it does not work on iOS 4.3.
The following alternative code works and gives the correct result:
NSDate *now = [NSDate date];
NSCalendar *myCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *firstDayOfTheWeek;
NSTimeInterval length;
[myCalendar rangeOfUnit:NSWeekCalendarUnit
startDate:&firstDayOfTheWeek
interval:&length
forDate:now];
NSDate *lastDayOfTheWeek = [firstDayOfTheWeek dateByAddingTimeInterval:length];
Update: The above code gives the (start of) the first day in the week and the (start of) the next week. If you add (length - 1)
instead of length
then you will get the end of the last day in the week (thanks @rmaddy!). Alternatively, you can add 6 days to the first day:
NSDate *now = [NSDate date];
NSDate *firstDayOfTheWeek;
NSCalendar *myCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[myCalendar rangeOfUnit:NSWeekCalendarUnit
startDate:&firstDayOfTheWeek
interval:NULL
forDate:now];
NSDateComponents *sixDays = [[NSDateComponents alloc] init];
[sixDays setDay:6];
NSDate *lastDayOfTheWeek = [myCalendar dateByAddingComponents:sixDays toDate:firstDayOfTheWeek options:0];
Remark: This code also handles the "start of week" correctly according to the locale.