I have a Mutable Dictionary which allows people to choose a selection of days of the week. Once a day has been selected the state is updated using numberWithBool.
When I NSLog the output it looks something like this:
{
day = Monday;
isSelected = 1;
},
{
day = Tuesday;
isSelected = 0;
},
{
day = Wednesday;
isSelected = 0;
},
{
day = Thursday;
isSelected = 0;
},
{
day = Friday;
isSelected = 0;
},
{
day = Saturday;
isSelected = 0;
},
{
day = Sunday;
isSelected = 1;
}
I would like to be able to extract the chosen days and produce the output in the form of a string. So in this example the output would be: Monday, Sunday
How can I do this?
My code for creating the dictionary is below:
NSMutableArray * tempSource = [[NSMutableArray alloc] init];
NSArray *daysOfWeek = [NSArray arrayWithObjects:@"Monday", @"Tuesday", @"Wednesday", @"Thursday", @"Friday", @"Saturday", @"Sunday",nil];
for (int i = 0; i < 7; i++)
{
NSString *dayOfWeek = [daysOfWeek objectAtIndex:i];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:dayOfWeek, @"day", [NSNumber numberWithBool:NO], @"isSelected",nil];
[tempSource addObject:dict];
}
[self setSourceArray:tempSource];
[tempSource release];
You can loop thru all of your items in the array and build a side-array only containing names of the day (1), or you can use a predicate and then KVC to extract the days directly (2).
Then join the components of the filtered array into a string.
Solution 1:
Solution 2:
As a side note, your way of doing this is quite strange. Why having an NSArray of NSDictionaries for this? As this is simple and a static-size array containing only BOOL, you may instead for this particular case simply use C array
BOOL selected[7]and nothing more.Then to have the name of the weekdays you should instead use the methods of
NSCalendar/NSDateFormatter/NSDateComponentsto get the standard names of the weekdays (automatically in the right language/locale of the user): create anNSDateusing aNSDateComponentfor which you simply define the weekday component, then use anNSDateFormatterto convert this to a string, choosing a string format that only display the weekday name.