user717452
user717452

Reputation: 111

Store Array of #s to NSUserDefaults, Add Checkmark to each cell row that matches a # in array

In an app I previously had help with here, I parse an XML located online, show only 1 item from the XML the first day, and add an item each day after that the app gets opened. I would like to be able to add a 'Mark As Read' action to each cell's detail view. This way, the user could read it, mark it as read, and on subsequent loads, a checkmark would appear next to each item loaded.

Since the app downloads the XML each time, here is the idea I thought may work the best to do this. I was thinking of having an array stored to a NSUserDefault Key. This array would have a number added to it based off what row they selected. If they selected row 1 and marked it, the array would add the #1 to it. If they then selected row 3 and marked it, the array would have 1 & 3 in it.

Is this something doable, and then in cellForRowAtIndexPath, have it add a checkmark to each row # that is included in the array?

I have the idea in my head, and if this works, just need a little guidance for implementing it. Thanks

UPDATE
Here is what little I do have so far. In the applicationDidFinishLaunchingWithOptions, I check if the NSUserDefault key 'checkedrows' exists. If not, I create it with an object of an empty array.

if (![defaults objectForKey:@"checkedrows"]) {
        [defaults setObject:@[] forKey:@"checkedrows"];
    }

The two main questions I have is how to in the cellForRowAtIndexPath get the numbers that are in the array, and if any rows match them, add a checkmark to it. Example: There are 5 rows in the tableview, and the array returns 0, 2, 4. So, I want the TableView to add a checkmark to first third and fifth cells.

The other main question is how to go about adding a number into the array, without deleting any of the old numbers.

Upvotes: 0

Views: 365

Answers (1)

bibo bode
bibo bode

Reputation: 1150

Absolutely!

You can use the setObject:forKey: method to write an NSArray object to NSUserDefaults, and objectForKey: to retrieve that array.

Now, simply listen out for

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

in your UITableViewDelegate, retrieve the array already existing in the NSUserDefaults, add the index that was just tapped (get this info. from the indexPath object) to the array, and simply write the array back to NSUserDefaults!

To add a checkmark to selected cells, use the following command inside thetableView:didSelectRowAtIndexPath: delegate method above:

[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;

Upvotes: 1

Related Questions