I have four array and they are full of NSNull elements: years (100 elements), months (12), days(31) and arrayString. When i choose two date I want put a string inside every array “arrayString” contained inside of every day of the period.
I choose two date and I do dateFormatter and I got first and last day, month an year:
I don’t write date1 and date2 but they are two NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd"];
int firstDay = [[dateFormatter stringFromDate:data1] intValue];
int lastDay = [[dateFormatter stringFromDate:data2] intValue];
[dateFormatter setDateFormat:@"MM"];
int firstMonth = [[dateFormatter stringFromDate:data1] intValue];
int lastMonth = [[dateFormatter stringFromDate:data2] intValue];
[dateFormatter setDateFormat:@"yyyy"];
int firstYear = [[dateFormatter stringFromDate:data1] intValue]-2011;
int lastYear = [[dateFormatter stringFromDate:data2] intValue]-2011;
NSString *string = @"firstString";
after I want add a NSString inside every array contained in every day of the period, it is possible because every position in the arrays there are NSNull elements that I put inside in viewdidload:
for (int k = firstYear ; k<lastYear + 1; k++){
for (int i = firstMonth; i < lastMonth+1; i++)
{
for (int j = firstDay; j < lastDay+1; j++)
{
[[days objectAtIndex:j] addObject: string];
}
[months replaceObjectAtIndex:i withObject:days];
}
[years replaceObjectAtIndex:k withObject:months];
}
This code work fine when I choose a period in the same month, because if I choose for example: 15/05/2011 to 25/05/2011 it’s ok, it fill the arrays string inside every day of the period.
But if I choose for example 28/05/2011 to 1/06/2011 there is a problem in the third loop; because “firstday” is 28 and “lastday” is 1, and it don’t entry inside at the loop; how can I solve this problem?
Given your comments on the question, I assume that you are looking for a way of associating strings (or any object, really) with given days. This association lends itself to an
NSDictionaryand dates are obviously best represented withNSDateinstances. With this in mind, I propose a different data structure.Rather than deeply nested arrays, you should consider the following, wherein
NSDateobjects are the dictionary’s keys and their respective values areNSArrayinstances containing the string for that specific point in time, not just the day:Now that you have your data stored in a suitable structure, you want to be able to query it for objects associated with a given day. For this, you could have the following method(s):
Now, if you wanted an array of all strings for today, you could simply call
[self stringsForDay:[NSDate date] withDictionary:theDictionary]and be done with it.This approach is more flexible than your alternative suggested in the question, as changing the granularity to weeks, months, years, etc. is now very simple.