Reputation: 41
I have a DetailViewController which is saving some Data to NSUserDefaults if the user wants. It is like kind of favorite list. Hier is the structure of the saved Defaults:
List = {
0002 = (
{
Picture = "link to picture.jpg";
Place = "London";
Title = "Flat with Balcony";
}
);
0003 = (
{
Picture = "link to picture.jpg";
Place = "Duesseldorf";
Title = "Roof Garden"
}
);
};
in viewDidLoad :
- (void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
// Save to the Dictionary
_myDict = [[userdefaults dictionaryRepresentation] objectForKey:@"List"];
NSLog(@"MYDICT : %@", _myDict);
// save only the keys which are 0002 and 0003 etc..
_keysArray = [_myDict allKeys];
NSLog(@"keysArray : %@", _keysArray);
// Print out the elements in keysArray
for(NSString *key in _keysArray){
NSLog(@"key : %@", key);
}
}
and in
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
// Return the number of rows in the section.
return [_keysArray count]; // gives 2
}
finally in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"favoritesCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
// this doesn't work gives only nothing ( not error) It is just empty
cell.textLabel.text = [_myDict valueForKeyPath:[NSString stringWithFormat:@"List.%@",_keysArray[indexPath.row]]];
//cell.textLabel.text = [_myDict valueForKeyPath:@"List"]; // this gives also nothing just empty
//How is it possible to reach a value of a key in nested NSUserdefaults
return cell;
}
How is it possible to reach a key value in nested Nsuserdefaults and use them in UITableView?
Upvotes: 0
Views: 175
Reputation: 3029
Try using [_myDict objectForKey:
[_keysArray objectAtIndex:indexPath.row]]. That will give you the value of one of the keys which is an array of a dictionary with 3 keys (Title, place and picture).
NSArray * keyValue = [_myDict objectForKey:[_keysArray objectAtIndex:indexPath.row]]:
cell.textLabel.text = [keyValue[0] objectForKey:@"Title"];
//will set the cell text to the Title value.
Upvotes: 1
Reputation: 1577
Try this code
NSArray *dataArray = [_myDict objectForKey:_keysArray[indexPath.row]];
NSDictionary *data = dataArray[0];
cell.textLabel.text = [data objectForKey@"Title"];
_myDict is List dictionary that contains two arrays at 0002 and 0003 so you need to first extract the array then get the first object that is your data. now you can access all the data of your object.
Upvotes: 1