将嵌套NSUSERDEFAULTS中的数据加载到UITABLEVIEW中

时间:2015-02-01 18:47:27

标签: ios objective-c uitableview nsdictionary nsuserdefaults

我有一个DetailViewController,如果用户需要,它会将一些数据保存到NSUserDefaults。这就像是一种最喜欢的名单。 Hier是保存的默认值的结构:

List =     {
        0002 =         (
                        {
                Picture = "link to picture.jpg";
                Place = "London";
                Title = "Flat with Balcony";
            }
        );
        0003 =         (
                        {
                Picture = "link to picture.jpg";
                Place = "Duesseldorf";
                Title = "Roof Garden"
            }
        );
    };
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);

    }
}

并在

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return  [_keysArray count]; // gives 2
}

终于在

- (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;
}

如何在嵌套的Nsuserdefaults中获取键值并在UITableView中使用它们?

2 个答案:

答案 0 :(得分:1)

尝试使用[_myDict objectForKey: [_ keysArray objectAtIndex:indexPath.row]]。这将为您提供其中一个键的值,该键是具有3个键(标题,地点和图片)的字典数组。

NSArray * keyValue = [_myDict objectForKey:[_keysArray objectAtIndex:indexPath.row]]:
cell.textLabel.text = [keyValue[0] objectForKey:@"Title"];
//will set the cell text to the Title value. 

答案 1 :(得分:1)

试试此代码

NSArray *dataArray = [_myDict objectForKey:_keysArray[indexPath.row]];
NSDictionary *data = dataArray[0];
cell.textLabel.text = [data objectForKey@"Title"];

_myDict是列表字典,包含0002和0003处的两个数组,因此您需要先提取数组然后获取第一个对象,即数据。现在您可以访问对象的所有数据。