Search code examples
iphoneuitableviewplistxcode4.4

Setting UITableViewCell Title from Plist String


Possible Duplicate:
sectioned UITableView sourced from a pList

I am having a hard time trying to set the text label of the cell to the values of the strings in my plist. The app crashes on cell.textlabel.text = [array objectAtIndex:indexPath.row];. I'm pretty sure everything else is good, just don't know that last part. Thanks in advance.

Here is my plist:

Root - Array
    Item 0 - Dictionary
        Key 0 - Array
            Item 0 - String - Value 0
        Key 1 - Array
            Item 1 - String - Value 1

Here are my tableview data source methods:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

return _objects.count;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

NSDictionary *dict = [_objects objectAtIndex:section];
return [dict.allValues count];

}

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

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];

NSArray *array = [_objects objectAtIndex:indexPath.section];
cell.textLabel.text = [array objectAtIndex:indexPath.row];

return cell;

}

Solution

  • well the structure of your _object is not clear. I am assuming it refers to Item 0 - Dictionary in the plist.

    in numberOfRowsInSection: you refer to it as a dictionary:

    NSDictionary *dict = [_objects objectAtIndex:section]
    

    while in cellForRowAtIndexPath: you refer to it as an array:

    NSArray *array = [_objects objectAtIndex:indexPath.section];
    

    anyway, if my assumption is correct then change the cellForRowAtIndexPath code to the following:

    NSDictionary *dict = [_objects objectAtIndex:indexPath.section];
    NSarray *array = [dict objectForKey:myKey]; //myKey is whatever key you are assigning
    cell.textLabel.text = [array objectAtIndex:indexPath.row];
    

    hope this helps.

    EDIT:

    well you can restructure your plist to achieve that. You basically just get rid of the dictionary level.. try something like this:

    Root - Array
        Item 0 - Array                   <-- this is a section
            Item 0 - String - Value 0    <-- this is a cell
        Item 1 - Array                   <-- section
            Item 0 - String - Value 1    <-- cell