So, I have an application that I'm building which includes a checklist of 100 items.
I wish to create an array of bools
which indicate whether or not an item is "checked", then save it to the device using NSUserDefaults
so it can be loaded each time the app is run.
I understand by reading around that you cannot store bool values in NSArrays so I opted of a mutable array which holds strings @"YES"
and @"NO"
... I'm almost certain this is a bad way of doing it but I'm out of ideas.
I create my array like this:
boolArrayOfCheckList = [[NSMutableArray alloc] initWithCapacity:100];
for (NSInteger i = 0; i < 100; i++){
[boolArrayOfCheckList addObject:[NSString stringWithFormat:@"NO"]];
}
When an item is checked using an IBAction
, it updates the array at the index associated with the button (this appears to be adding to the array instead of replacing the object at said index :( ...):
[boolArrayOfCheckList insertObject:[NSString stringWithFormat:@"YES"] atIndex:0];
Then save the array like this:
[[NSUserDefaults standardUserDefaults] setObject:boolArrayOfCheckList forKey:@"myBoolArray"];
When I reload the application, the ViewdidLoad
loads the key:
NSMutableArray *boolArrayOfCheckList = (NSMutableArray *)[[NSUserDefaults standardUserDefaults] objectForKey:@"myBoolArray"];
and comparing the element like this and loading the items check/uncheck accordingly:
if([[boolArrayOfCheckList objectAtIndex:0] isEqualToString:@"YES"]) ... //do this
But I'm getting some funny results when I add strings and I'm having trouble loading the data again.
There must be a better more efficient way of storing a checklist in an array that can be saved/updated accordingly. How can this be done?
Thank you.
Update
Just noticed I was inserting instead of replacing, so that explains the array getting bigger instead of replacing the object at a specific index. Now doing this:
[boolArrayOfCheckList replaceObjectAtIndex:1 withObject:[NSString stringWithFormat:@"YES"]];
You can use the NSNumber BOOL
@YES
and@NO
instead of anNSString
of @"YES" and @"NO".To get the value:
or