user3310076 user3310076 - 4 months ago 16
iOS Question

Dynamic rows for each section

How to calculate number of rows for each section and populate it's data. Below is the data.

<__NSCFArray 0x7fadb3e73a60>(
{
AMID = "";
AMName = "xyz";
records = (
{
EId = 100;
EMName = "abc";
EName = "Ename1";
}
);
EGroupId = 001;
EGroupName = "SectionName1";
stat = G;
},

{
AMID = "";
AMName = "zyx";
records = (
{
EId = 144;
EMName = "namename";
EName = "somestring";
},
{
EId = 159;
EMName = "somestring";
EName = "somestring";
},
{
EId = 161;
EMName = "somestring";
EName = "somestring";
}

);
EGroupId = 86;
EGroupName = "SectionName2";
stat = Y;
}
)


From the above data, i want the "EGroupName" value in sections and dynamically count the numberofrowsinsection for each section(in this case, it's 'SectionName1 and SectionName2).
Final output Should Be like,

**SectionName1**
return 1;
**SectionName2**
return 3;


really appreciate your help.

Answer

The array, once converted into objects will be an array of dictionaries, where each dictionary contains an array, and each contains a string value that can be used as a section name. That's a perfectly good datasource for a multi-section table view.

After parsing the JSON, you'll have an objective c collection, call it:

NSArray *parsedObject;

The number of sections is:

parsedObject.count;

The title of a section at an indexPath is:

parsedObject[indexPath.section][@"EGroupName"]

The number of rows in a section is:

NSArray *sectionArray = parsedObject[section][@"records"];
[sectionArray count]

The model item at a given indexPath is:

NSArray *sectionArray = parsedObject[indexPath.section][@"records"];
sectionArray[indexPath.row];

EDIT to go a little deeper, the section array itself is an array of dictionaries, so...

NSArray *sectionArray = parsedObject[indexPath.section][@"records"];
NSDictionary *modelItem = sectionArray[indexPath.row];

NSNumber *itemId = modelItem[@"EId"];
NSNumber *itemEMName = modelItem[@"EMName"];
NSNumber *itemName = modelItem[@"EName"];

// if the table cell is a just a vanilla UITableViewCell...
cell.textLabel.text = itemName;
cell.detailTextLabel.text = itemEMName;

EDIT AGAIN

Remember, all of your datasource code must follow this pattern, so to get section level attributes from the data...

NSString *engagementGroupString = engagementGroupDataArray[section][@"EGroupName"];
NSString *engagementManagerString = engagementGroupDataArray[section][@"AMName"];