I’m working on a project that needs to check the time difference from a first launch date. I’m using the NSDayCalendarUnit and NSWeekCalendarUnit. Basically for the first 2 weeks on every second day I want to perform something. The object I’m using needs to be in a certain state for each two days at a time.
So for example
Day 1 & 2, Week 0 - State 1
Day 3 & 4, Week 0 - State 2
...
Day 1 & 2, Week 1 - State 8
Day 3 & 4, Week 1 - State 9
Here is my code:
// get the data/time difference from the first launch
int daysDifferent = [[dateDifferenceInfo objectForKey:@"days"] intValue];
int weeksDifferent = [[dateDifferenceInfo objectForKey:@"weeks"] intValue];
if(daysDifferent == 2 | daysDifferent == 3 && !weeksDifferent && _dot.age != 2){
// set state
}
if(daysDifferent == 4 | daysDifferent == 5 && !weeksDifferent && _dot.age != 3){
// set state
}
if((daysDifferent == 6 && weeksDifferent == 0 | daysDifferent == 0 && weeksDifferent == 1) && _dot.age != 4){
// set state
}
if(daysDifferent == 0 | daysDifferent == 1 && weeksDifferent == 1 && _dot.age != 5){
// set state
}
if(daysDifferent == 2 | daysDifferent == 3 && weeksDifferent == 1 && _dot.age != 6){
// set state
}
if(daysDifferent == 4| daysDifferent == 5 && weeksDifferent == 1 && _dot.age != 7){
// set state
}
if((daysDifferent == 6 && weeksDifferent == 1 | daysDifferent == 0 && weeksDifferent == 2) && _dot.age != 8){
// set state
}
if(weeksDifferent >= 2 && !(daysDifferent % 2)){
// set state
}
Side note: I know it’s bad code, I plan to replace this with switch cases, I just need to logic sorted first.
My question is is there a better way of calculating this kind of pattern?
I’m not totally clear on your goal, as you say:
Where I would have thought it would be
So if your example is right, the calculation is different.
Based on the simpler example, I would calculate the time interval since the first date, and divide by twice the length of a day, taking the floor. That is the state:
If, on the other hand, it really is as you have described, the approach I would use as fast and simple would be to do a similar calculation – leaving out the 0.5 factor in the last line, and then use a simple table lookup to get the state from the day: