Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested NSUserDefaults arrays read/write

I have the following structure of data:

- Cards
 -- Item 0
  --- Name: Card Name
  --- Number: Card Number
  --- Type: Card Type
 -- Item 1
  --- Name: Card Name
  --- Number: Card Number
  --- Type: Card Type
...

The user can add as many cards as he wants, so Name, Number and Type are user defined.

1st question is, how can I write this data to a NSUserDefauls (nested like this)

2nd Question is, and how can I retrieve this data and show the name of each card in a table view. (I already have the tableview set and working, so it's a matter of getting the data from the NSUserDefaults).

Any code example is well appreciated.

Thanks

like image 521
gmogames Avatar asked Dec 07 '25 07:12

gmogames


1 Answers

To create this structure is quite simple, you create a dictionary that has an array value for your key `Cards'. Example below..

NSMutableDictionary *cards = [NSMutableDictionary dictionary];
NSMutableArray *cardArray = [NSMutableArray array];

NSMutableDictionary *item = [NSMutableDictionary dictionary];
[item setValue:@"Card Name" forKey:@"Name"];
[item setValue:@"Card Number" forKey:@"Number"];
[item setValue:@"Card Type" forKey:@"Type"];

[cardArray addObject:item];
[cards setValue:cardArray forKey:@"Cards"];

[[NSUserDefaults standardUserDefaults] setValue:cards forKey:@"user_cards"];
[[NSUserDefaults standardUserDefaults] synchronize];

In order to retrieve your cards, you would do something like..Assuming self.cards is an NSMutableArray ivar..

NSMutableDictionary *stored = [[NSUserDefaults standardUserDefaults] valueForKey:@"user_cards"];

self.cards = [stored valueForKey:@"Cards"];

Your tableview should use cards ivar to populate your data, like below.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    ...... 

    //Now we populate each row of the cell with each `card` Name.
  cell.textLabel.text = [[self.cards objectAtIndex:[indexPath row]] valueForKey:@"Name"];

   .....
}

To resave any newly added cards to your stored dictionary you would do something like this..

NSMutableDictionary *newCard = [NSMutableDictionary dictionary];
[newCard setValue:@"Card Name" forKey:@"Name"];
[newCard setValue:@"Card Number" forKey:@"Number"];
[newCard setValue:@"Card Type" forKey:@"Type"];

[self.cards addObject:newCard];

[[NSUserDefaults standardUserDefaults] valueForKey:@"user_cards"] setValue:self.cards forKey:@"Cards"];
[[NSUserDefaults standardUserDefaults] synchronize];

If this has helped with your questions, please accept it as an answer.

like image 80
skram Avatar answered Dec 08 '25 21:12

skram