How to calculate dynamic no of rows in each section - ios

I am developing iPhone app and i got stuck at one point need your help,
I have tableview with dynamic sections and dynamic no of rows in each section.
Here is my json data format: http://pastebin.com/jmsq1pxu
I have fetched all this data in my array,
now i have calculated number of sections in tableview based on SpecGroupLabel key:
I found section count as 10
General,
Body,
Display,
Memory,
Camera,
Connectivity,
OS,
Processor,
Battery,
Sound
Now in each section i want to calculate no of rows.
Here in this case 1st section is General 2nd is Body 3rd is Display and so on upto 10th section Sound i want to calculate no of rows in each section ?
and finally how should i display different section and it's row in cellForRowAtIndexPath ?
Please help and thanks in advance.

I'll explain in detail
Suppose you have the following json
{
data:[
{
label:Fruit,
name: Orange,
},
{
label:Month,
name: June,
},
{
label:Color,
name: Blue,
},
{
label:Color,
name: Red,
},
{
label:Fruit,
name: Apple,
},
{
label:Color,
name: Pink,
},
{
label:Fruit,
name: Mango,
},
{
label:Month,
name: May,
},
{
label:Color,
name: White,
},
]
}
And you want your table to look like
Fruit
Orange
Apple
Mango
Month
June
May
Color
Blue
Red
Pink
White
NSMutableDictionary *dict;
- (void)viewDidLoad
{
[super viewDidLoad];
dict = [[NSMutableDictionary alloc] init];
NSArray *jsonArray ;// this is your data json array
for (int i = 0; i < jsonArray.count; i++) {
NSDictionary *dataDict = [jsonArray objectAtIndex:i];
NSString *getLabel = [dataDict objectForKey:#"label"];
if([dict objectForKey:getLabel] == NULL){
//this label is not present in your dict, so that means its a new section.
NSMutableArray *newArray = [[NSMutableArray alloc] init];
[newArray addObject:[dataDict objectForKey:#"name"]];
[dict setObject:newArray forKey:getLabel];
}else{
// already added to the dictionary
NSMutableArray *getArray = [dict objectForKey:getLabel];
[getArray addObject:[dataDict objectForKey:#"name"]];
}
}
// Do any additional setup after loading the view, typically from a nib.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return dict.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSArray *getArray = [dict.allValues objectAtIndex:section];
return getArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection: (NSInteger)section{
return 40.0;
}
-(UIView*) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 40.0)];
UILabel *sectionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 40.0)];
sectionLabel.text = [dict.allKeys objectAtIndex:section];
[view addSubview:sectionLabel];
return view;
}
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
NSArray *getArray = [dict.allValues objectAtIndex:indexPath.section];
cell.textLabel.text = [getArray objectAtIndex:indexPath.row];
}

the number of the groups:
NSInteger _numberOfGroups = [[_array valueForKeyPath:#"#distinctUnionOfObjects.SpecGroupLabel"] count];
the number of the items in a particular group (e.g. "General"):
NSInteger _numberOfItemsInAGroup = [[_array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSDictionary * evaluatedObject, NSDictionary *bindings) {
return [[evaluatedObject valueForKey:#"SpecGroupLabel"] isEqualToString:#"General"]; // or Body, Display, Memory, Camera, Connectivity, etc...
}]] count];
NOTE: you can read more about KVC here and predicates here.

You need to create an array of arrays. Each array will represent a section. Within each array add your data for an individual row.
To get number of rows in a section:
NSInteger rows = array[section].count
In cellForRowAtIndexPath use the indexpath
CustomObject *object = [array[indexPath.section] objectAtIndex:indexPath.row]

Related

Custom tableview cell multiple rows

This is my json data. Here it is Restaurant name coming one and line name coming 2 some times line name coming more then how to print the data in custom cell.please. help me
"currency": "$",
"state": "sale",
"total": 243.1,
"name": "a1238",
"restaurant_name": "\"Food Court\" Biergarten",
"date": "2016-10-16 07:52:07",
"table_no": null,
"so_id": 238,
"lines": [
{
"line_status": "pending",
"line_id": 2536,
"line_price": 1,
"line_qty": 1,
"line_name": "Käse"
},
{
"line_status": "pending",
"line_id": 2579,
"line_price": 7.8,
"line_qty": 2,
"line_name": "3 Musketiere (3x verschiedene Hefe 0,3l)"
},
Try like this:
First get all values from your response in NSMutableArray what you want
#interface ViewController ()
{
NSMutableArray *restaurentsNamesArray;
NSMutableArray *linesArray;
NSMutableArray *linesCountArray;
}
After that in viewDidLoad add values to those mutable arrays which you got from your response
- (void)viewDidLoad {
[super viewDidLoad];
restaurentsNamesArray = [[NSMutableArray alloc]init];
linesArray = [[NSMutableArray alloc]init];
linesCountArray = [[NSMutableArray alloc]init];
NSError *error;
// Do the stuff for get response from url here.
// And give that request below.
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSDictionary *main = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSDictionary *result = [main valueForKey:#"result"];
NSArray *saleorders = [result valueForKey:#"saleorders"];
for (NSDictionary *dict in saleorders){
[restaurentsNamesArray addObject:[dict valueForKey:#"restaurant_name"]];
[linesArray addObject:[dict valueForKey:#"lines"]];
}
NSLog(#"%#",restaurentsNamesArray);
NSLog(#"%#",linesArray);
}
Now all you want is implement table view delegate methods like below:
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [restaurentsNamesArray count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSArray *array;
if (linesArray.count > section){
array = [linesArray objectAtIndex:section];
}
return array.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [[UITableViewCell alloc]init];
NSArray *array;
array = [linesArray objectAtIndex:indexPath.section];
NSDictionary *dict = [array objectAtIndex:indexPath.row];
cell.textLabel.text = [dict valueForKey:#"line_name"];
cell.detailTextLabel.text = [dict valueForKey:#"line_id"];
return cell;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [restaurentsNamesArray objectAtIndex:section];
}
Here I'm just populating restaurant names in tableView section header as NSString.
If you want exactly like android what you shown above you have to implement below methods instead of -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section this method
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 50)];
[headerView setBackgroundColor:[UIColor darkGrayColor]];
UILabel *tempLabel=[[UILabel alloc]initWithFrame:CGRectMake((headerView.frame.size.width/2)-47,-32,300,94)];
tempLabel.backgroundColor=[UIColor clearColor];
tempLabel.shadowColor = [UIColor blackColor];
tempLabel.shadowOffset = CGSizeMake(0,2);
tempLabel.textColor = [UIColor whiteColor];
tempLabel.font = [UIFont fontWithName:#"Helvetica" size:17.0];
tempLabel.font = [UIFont boldSystemFontOfSize:17.0];
tempLabel.text= [restaurentsNamesArray objectAtIndex:section];
[headerView addSubview:tempLabel];
return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
{
return 35;
}
Like the same way I'm just populating lineName in cell.textLabel
If you want to do more , just create custom tableViewCell and create layout how you want.
that's it.
Cheers.
Use your restaurant array for section
numberOfSectionsInTableView{}
and your "lines": [{}] array for
numberOfRowsInSection{}
You may get better idea from code mentioned below
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number restaurant count
return [restaurantArray count];
}
and for multiple rows considering you have restaurant as object:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of lines count.
return [objRestaurant.Lines count];
}
First of all create an array of Restaurant type an fetch the data from json and add it into an array just like that
var RestaurantArray = [Restaurant]()
for index in 0..<JSON["data"].count
{
let address = String(JSON["data"][index]["Address"])
let CityId = JSON["data"][index]["CityId"].int
let Description = String(JSON["data"][index]["Description"])
let Name = String(JSON["data"][index]["Name"])
//create an object of Restaurant type and map the data into object and then add it into array that we have created .
var RestaurantModel:Restaurant?
RestaurantModel.address = address
RestaurantModel.cityID = cityId
RestaurantModel.Description = Description
RestaurantArray.append(RestaurantModel)
}
now use this array in your tableview
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return RestaurantArray.count
}
I hope this will make a lot of sense to you
Cheers

How to get actual value of NSMutableArray not Index in UITableview in Objective c

I am new in iOS and I am facing a problem regarding to get the ID of array after searching. I need to get the actual value of array after searching but when I search the content of array it give me the index of array which is at present in tableview. My code is like this :
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
arrOfColor=[NSMutableArray arrayWithObjects:#"Red",#"Green",#"Blue",#"Gray",#"Black",#"White",#"Yellow",#"Brown",#"Pink",nil]; //Hear arrofColor is NSMutableArray.
idarray2 =[NSMutableArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"7",#"8",#"9", nil]; //Hear idarray is NSMutableArray.
[self.searchTextField addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(isFilter)
{
return [searchArray count];
}
else
return [arrOfColor count];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:#"cell"];
if(!cell)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
if(isFilter)
{
cell.textLabel.text=[searchArray objectAtIndex:indexPath.row];
}
else
{
cell.textLabel.text=[arrOfColor objectAtIndex:indexPath.row];
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(isFilter)
{
_searchTextField.text=[searchArray objectAtIndex:indexPath.row];
idlbl.text=[idarray2 objectAtIndex:indexPath.row];
}
else
{
_searchTextField.text=[arrOfColor objectAtIndex:indexPath.row];
idlbl.text=[idarray2 objectAtIndex:indexPath.row];
}
}
-(void)textFieldDidChange:(UITextField *)textField
{
searchTextString=textField.text;
[self updateSearchArray:searchTextString];
}
-(void)updateSearchArray:(NSString *)searchText
{
if(searchText.length==0)
{
isFilter=NO;
}
else{
isFilter=YES;
searchArray=[[NSMutableArray alloc]init];
for(NSString *string in arrOfColor){
NSRange stringRange=[string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location !=NSNotFound){
[searchArray addObject:string];
}
}
[self.colorTableview reloadData];}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
Before search value of array is 6
But When I search it it's ID change to 1.
So, How can I get the 6 id even after search. Thanks in Advance!
You have to create a new array.
A sample code:
NSMutableArray *arrOfColor=[NSMutableArray arrayWithObjects:#"Red",#"Green",#"Blue",#"Gray",#"Black",#"White",#"Yellow",#"Brown",#"Pink",nil]; //Hear arrofColor is NSMutableArray.
NSMutableArray *idarray2 =[NSMutableArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"7",#"8",#"9", nil];
NSMutableArray *searchArrayColor =[[NSMutableArray alloc]init];
NSMutableArray *searchArrayId =[[NSMutableArray alloc]init];
for(NSString *string in arrOfColor){
NSRange stringRange=[string rangeOfString:#"r" options:NSCaseInsensitiveSearch];
if(stringRange.location !=NSNotFound){
[searchArrayColor addObject:string];
NSInteger index = [arrOfColor indexOfObject:string];
[searchArrayId addObject:[idarray2 objectAtIndex:index]];
}
}
NSLog(#"%#",arrOfColor);
/*2016-10-14 12:15:44.618 objC[1855:50348] (
Red,
Green,
Blue,
Gray,
Black,
White,
Yellow,
Brown,
Pink
)*/
NSLog(#"%#",idarray2);
/*2016-10-14 12:15:44.619 objC[1855:50348] (
1,
2,
3,
4,
5,
6,
7,
8,
9
)*/
NSLog(#"===========");
NSLog(#"%#",searchArrayColor);
/*
2016-10-14 12:15:44.619 objC[1855:50348] (
Red,
Green,
Gray,
Brown
)
*/
NSLog(#"%#",searchArrayId);
/*
2016-10-14 12:15:44.619 objC[1855:50348] (
1,
2,
4,
8
)
*/
so you are showing that id like,
idlbl.text=[idarray2 objectAtIndex:indexPath.row];
as you said in comment in your question then it will definitely prints 1 because after search your tableview have only one row so, indexPath.row will be 0, so [idarray2 objectAtIndex:indexPath.row]; means first object of idarray2 and it is 1. So, it will return 1.
Now if you want relevant id then you can do something like,
NSUInteger index = [arrOfColor indexOfObject:#"white"]; // pass color here i have take static value for demonstration you should pass dynamic value depend on search
NSString *yourId = [idarray2 objectAtIndex:index];
idlbl.text=yourId;

Adding sections to tableview, index out of bounds error

In this app, I download data from Parse. That data is a list of 5 Messages, each with a category. There are 4 different categories as two of the messages have the same category. I want to put that data into sections on a tableview. Since the data is not ready for sectioning, I had to create 2 mutable arrays that act like index look ups. (followed this guide: https://parse.com/questions/using-pfquerytableviewcontroller-for-uitableview-sections)
Problem: I'm getting this error:
-[__NSArrayM objectAtIndex:]: index 8 beyond bounds [0 .. 4]'
Question is, why am I getting this error and how do I fix it?
I've located the exact line that is the problem. First, here is what you need.
1st Mutable Dictionary:
self.sectionToCategoryMap //This property maps the sections titles to the row indeces for the data. The output it looks like this: (read as, get the 1st category header from object at index 0)
0 = "Section Header 1";
24 = "Section Header 2";
16 = "Section Header 3";
32 = "Section Header 4";
2nd Mutable Dictionary:
self.sections // This maps what items are in what section(category). Output looks like this:
"category 1" =(32);
"category 2" =(24);
"category 3" =(16);
"category 4" =(0,8);
These two Dictionaries are created by this code:
- (void)prepSections:(id)array {
[self.sections removeAllObjects];
[self.sectionToCategoryMap removeAllObjects];
self.sections = [NSMutableDictionary dictionary];
self.sectionToCategoryMap = [NSMutableDictionary dictionary];
NSInteger *section = 0;
NSInteger *rowIndex = 0;
for (MessageItem *messageItem in self.messageList) {
NSString *category = [messageItem valueForKey:#"messageCategory"]; //retrieves category for each message -1st regulator
NSMutableArray *objectsInSection = [self.sections objectForKey:category]; //assigns objectsinsection value of sections for current category
if (!objectsInSection) {
objectsInSection = [NSMutableArray array];
// this is the first time we see this category - increment the section index
//literally it ends up (0:Regulatory)
[self.sectionToCategoryMap setObject:category forKey:[NSNumber numberWithInt:rowIndex]];
section++;
}
[objectsInSection addObject:[NSNumber numberWithInt:(int)rowIndex++]]; //adds message to objects in section
[self.sections setObject:objectsInSection forKey:category]; //adds dict of objects for category
}
}
The error is happening in my in cellForRowAtIndexPath below, specifically the line:
NSNumber *rowIndex = [rowIndecesInSection objectAtIndex:indexPath.row];
(note: categoryForSection is a helper method I defined, its implementation is also below.)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSString *category= [self categoryForSection:indexPath.section];
NSArray *rowIndecesInSection = [self.sections objectForKey:category];
NSNumber *rowIndex = [rowIndecesInSection objectAtIndex:indexPath.row]; //pulling the row indece from array above
//gets to 3 and breaks!!!
messageItem = [self.messageList objectAtIndex:[rowIndex intValue]];
[cell configMessageCell:messageItem indexPath:indexPath];
return cell;
}
For good measure, here is the rest of my code.
- (NSString *) categoryForSection:(NSInteger*)section { //takes section # and returns name of section.
return [self.sectionToCategoryMap objectForKey:[NSNumber numberWithInt:(int)section]];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return (unsigned long)self.sections.allKeys.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSString *category = [self categoryForSection:section];
NSArray *rowIndecesInSection = [self.sections objectForKey:category];
return [rowIndecesInSection count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *category =[self categoryForSection:section];
return category;
}
Please help me fix this. It has had me stuck for days! Thank you!
Matt
I think the problem lies in declaring these as pointers:
NSInteger *section = 0;
NSInteger *rowIndex = 0;
(Note the weird multiples of 8 in the numbers in your dictionaries - that's because pointer arithmetic works differently from "normal" arithmetic). Try with
NSInteger section = 0;
NSInteger rowIndex = 0;

separate JSON to uitableview sections

I have some JSON data that I am getting from my database. I can pull it fine and load it into my table view. my issue is separating my JSON data so I can section the tableview.
JSON
[{"id":"1","name":"steve mans","phoneNumber":"(559)123-4455","showNumber":"1","greenCard":"1","expiration":"2014-02-15","driver":"1","paid":"1","watch":"1"},
{"id":"2","name":"myself and me","phoneNumber":"(559)321-6784","showNumber":"1","greenCard":"1","expiration":"2013-10-18","driver":"0","paid":"0","watch":"2"},
{"id":"4","name":"tod bellesmithson","phoneNumber":"(559)678-3421","showNumber":"0","greenCard":"1","expiration":"2013-11-22","driver":"1","paid":"0","watch":"2"},
{"id":"3","name":"John Smith","phoneNumber":"(559)123-1234","showNumber":"1","greenCard":"0","expiration":"2013-10-08","driver":"0","paid":"1","watch":"3"},
{"id":"5","name":"greg smith","phoneNumber":"559 345-1234","showNumber":"1","greenCard":"1","expiration":"2013-10-08","driver":"0","paid":"1","watch":"3"}]
What I am trying to do is, separate this data into three sections in my tableview. So I thought create three different tables and load each table into a different section of the tableview. But the information is the same in each one (id, name, phone etc.) So I ended up with one table and added a column that designates what shift people work, 'watch'. So how do I separate the data by using the watch column, so in my tableview i will have:
section one
people who work night shift
section two
people who work morning
section three
night shift
Try with this code:
NSArray *data = (NSArray)[NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&error];
NSMutableArray *morningShift = [NSMutableArray array];
NSMutableArray *noonShift = [NSMutableArray array];
NSMutableArray *nightShift = [NSMutableArray array];
for (int i=0; i< [data count]; i++)
{
NSDictionary *item = data[i];
if (#"1" == item[#"watch"] )
{
[morningShift addObject:item];
} else if (#"2" == item[#"watch"] )
{
[noonShift addObject:item];
} else if (#"3" == item[#"watch"] )
{
[nightShift addObject:item];
}
}
try this
NSMutableArray *tableData = [NSMutableArray alloc] init];
NSArray* nameArr = [NSArray arrayWithObjects: #"1", #"2",#"3",nil];
for(int i=0; i<[nameArr count]; i++)
{
[tableData addObject:[jsonArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"watch = %#",[nameArr objectAtIndex:i]]] ];
}
TableView Delegate Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [tableData count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[tableData objectAtIndex:section ] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell= nil;
//implement your logic to display the cell item;
NSArray sectionData = [tableData objectAtIndex:indexPath.section];
NSArray rowData = [sectionData objectAtIndex:indexPath.row];
return cell;
}
Please note i have not compiled the code. There is a chance of compilation error.
check for section in your cellForRowAtIndexPath method and load data accordingly,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//initialize cell
if (indexPath.section == 0){
// load data
}
return cell;
}

Accessing NSMutableArray Objects For Using On TableView

I started develop an app which is using WCF service with JSON data. I got the data from WCF service but I didn't use it as I want.
here is the JSON data:
{"MenuDoldurAndroidResult":[
{"menu_description":"Turkish Pizza","menu_title":"L Pizza","menu_price":"26 TL"},{"menu_description":"Italiano Pizza","menu_title":"L Pizza","menu_price":"27 TL"},{"menu_description":"Extravaganza","menu_title":"L Pizza","menu_price":"29 TL"},{"menu_description":"Pepporoni Pizza","menu_title":"L Pizza","menu_price":"28 TL"},{"menu_description":"Turkish Pizza","menu_title":"S Pizza","menu_price":"12 TL"},{"menu_description":"Italiano Pizza","menu_title":"S Pizza","menu_price":"13 TL"},{"menu_description":"Extravaganza","menu_title":"S Pizza","menu_price":"15 TL"},{"menu_description":"Pepporoni Pizza","menu_title":"S Pizza","menu_price":"14 TL"}
]}
What I want:
If there are 2 title here, there must be 2 section in table view. Every item must be in their section.
Like this:
-L Pizzas
Turkish Pizza 26 TL
Italiano Pizza 27 TL
Extravaganza Pizza 29 TL
Pepperoni Pizza 28 TL
-S Pizzas
Turkish Pizza 12 TL
Italiano Pizza 13 TL
Extravaganza Pizza 15 TL
Pepperoni Pizza 14 TL
How can I access this item and display like this ?
- (void)viewDidLoad
{
[super viewDidLoad];
//I posted request to service here. I didn't write these parts of code.
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
NSMutableArray *array= [json objectForKey:#"MenuDoldurAndroidResult"];
menu = [[NSMutableArray alloc] initWithCapacity:3];
NSString *descriptionTemp;
NSString *titleTemp;
NSString *priceTemp;
for(int i=0; i< array.count; i++)
{
NSDictionary *menuList= [array objectAtIndex:i];
titleTemp = [menuList objectForKey:#"menu_title"];
descriptionTemp = [menuList objectForKey:#"menu_description"];
priceTemp = [menuList objectForKey:#"menu_price"];
[menu addObject:[NSArray arrayWithObjects:titleTemp,descriptionTemp,priceTemp,nil]];
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 2;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 2;
}
-(NSString *)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section{
if (section==0) {
return #"L Pizzas";
}
else{
return #"S Pizzas";
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];
cell.textLabel.text = [menu objectAtIndex: indexPath.row];
return cell;
}
If your content is static you can try using the answer by Sunny. But if is dynamic it's better to store the data in a different way. Obviously L pizza and S pizza seems to be a category and the rest are like category items.
You need to make a collection of the categories. Demo Project Source Code
- (void)viewDidLoad
{
[super viewDidLoad];
//I posted request to service here. I didn't write these parts of code.
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
NSMutableArray *allPizzas = [json[#"MenuDoldurAndroidResult"] mutableCopy];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"menu_price"
ascending:YES
selector:#selector(compare:)];
[allPizzas sortUsingDescriptors:#[sortDescriptor]];
NSMutableArray *pizzaCategories = [#[]mutableCopy];
//Find unique categories in all the pizzas
NSSet* categories = [NSSet setWithArray: [allPizzas valueForKey:#"menu_title"]];
//Enumerate to form a new reformatted category array
for (NSString *categoryTitle in categories)
{
//Predicate is used to find the items that come under current category
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"menu_title == %#",categoryTitle];
NSArray *categoryItems = [allPizzas filteredArrayUsingPredicate:predicate];
//New dictionary with name of category and category items are formed
NSDictionary *categoryDict = #{#"menu_title":categoryTitle,#"pizzas":categoryItems};
[pizzaCategories addObject:categoryDict];
}
//Assign the new formatted category array to the instance variable for holding categories.
self.categories = pizzaCategories;
}
Modify the datasource of tableView for the new structure
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//The count of categories will give number of sections
NSUInteger sections = [self.categories count];
return sections;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//The number of items in a category is calculated
NSDictionary *category = self.categories[section];
return [category[#"pizzas"] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
//Title for the category
NSDictionary *category = self.categories[section];
return category[#"menu_title"];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
NSDictionary *category = self.categories[indexPath.section];
NSArray *categoryItems = category[#"pizzas"];
NSDictionary *categoryItem = categoryItems[indexPath.row];
cell.textLabel.text = categoryItem[#"menu_description"];
cell.detailTextLabel.text = categoryItem[#"menu_price"];
return cell;
}
You can also use the free Sensible TableView framework to fetch the data from the web service and automatically display it in your table view.

Resources