iOS - Simple Table Sections with Array Data - ios

I'm just starting with iOS/Xcode and have been Googling/Youtubing for an hour and can't find a matching tutorial. All I'm trying to do right now is display a table with a list of exercises (rows) that are grouped by bodypart (sections). The bodypart sections will never change, but the user will be able to add a custom exercise to a bodypart.
Now, I'm assuming that I need an array for the sections and also an array for exercises...creating those is simple enough. I'm running into a problem assigning exercises to specific sections. Here's an example of the faulty code that when rendered, displays both exercises under both sections...also there aren't any section names being generated in the table so I'm not sure where that comes into play either.
Here's a screenshot of the result (as a side note, not sure why my nav controller isn't rendering): http://i.imgur.com/icoJgEq.jpg
Create the individual items:
#property NSString *exerciseName;
#property NSString *exerciseCategoryName;
Create/Allocate the arrays:
#property NSMutableArray *exerciseCategories;
#property NSMutableArray *exercises;
self.exerciseCategories = [[NSMutableArray alloc]init];
self.exercises = [[NSMutableArray alloc]init];
Fill the arrays with some default data:
- (void)loadInitialData {
FNTExerciseCategories *category1 = [[FNTExerciseCategories alloc]init];
category1.exerciseCategoryName = #"Chest";
[self.exerciseCategories addObject:category1];
FNTExerciseCategories *category2 = [[FNTExerciseCategories alloc]init];
category2.exerciseCategoryName = #"Biceps";
[self.exerciseCategories addObject:category2];
FNTExercises *exercise1 = [[FNTExercises alloc]init];
exercise1.exerciseName = #"Bench Press";
[self.exercises addObject:exercise1];
FNTExercises *exercise2 = [[FNTExercises alloc]init];
exercise2.exerciseName = #"Barbell Curl";
[self.exercises addObject:exercise2];
}
Load the data:
[self loadInitialData];
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return [self.exerciseCategories count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.exercises count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ExercisePrototypeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
MFTExercises *exercise = [self.exercises objectAtIndex:indexPath.row];
cell.textLabel.text = exercise.exerciseName;
return cell;
}
Thank you very much to anybody that can chime in!

Actually in tableView:numberOfRowsInSection: you are returning the count of the entire exercises array. So with your sample data you would have two rows per section. Try making an array of exercises for every section and then code something like the following:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if (section == 0) {
return [self.chestExercises count];
}
else if (section == 1) {
return [self.bicepsExercises count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ExercisePrototypeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
MFTExercises *exercise;
if (indexPath.section == 0) {
exercise = [self.chestExercises objectAtIndex:indexPath.row];
}
else if (indexPath.section == 1) {
exercise = [self.bicepsExercises objectAtIndex:indexPath.row];
}
cell.textLabel.text = exercise.exerciseName;
return cell;
}
In this case the chestExercises array would only contain the "Bench Press"-exercise and the bicepsExercises would only contain the "Barbell Curl"-exercise. So you would get one row per section.
For achieving that the sections have titles you would need to implement the method
- (NSString *)tableView:(UITableView *)aTableView titleForHeaderInSection:(NSInteger)section {
return [self.exerciseCategories objectAtIndex:section];
}
which gives the sections the title according to the names stored in the array.
A more sophisticated way to build your datasource would be to create a NSDictionary with the section names as the keys (bodyparts) and the values being arrays containing the exercises for the bodypart. For instance if your categories are merely strings you could build such a dictionary with your sample data (for the purpose of demonstration I added another exercise):
FNTExerciseCategories *category1 = [[FNTExerciseCategories alloc]init];
category1.exerciseCategoryName = #"Chest";
[self.exerciseCategories addObject:category1];
FNTExerciseCategories *category2 = [[FNTExerciseCategories alloc]init];
category2.exerciseCategoryName = #"Biceps";
[self.exerciseCategories addObject:category2];
FNTExercises *exercise1 = [[FNTExercises alloc]init];
exercise1.exerciseName = #"Bench Press";
FNTExercises *exercise2 = [[FNTExercises alloc]init];
exercise2.exerciseName = #"Barbell Curl";
FNTExercises *exercise3 = [[FNTExercises alloc]init];
exercise3.exerciseName = #"Another Exercise";
// the instance variable self.exercises is a NSMutableDictionary now of course
self.exercises = [[NSMutableDictionary alloc] init];
exercises[category1.exerciseCategoryName] = #[exercise1];
exercises[category2.exerciseCategoryName] = #[exercise2, exercise3];
The advantage here is that you now have one dictionary containing all arrays that contains all your data. So as you're adding more data you don't have to change your implementation of the tableView datasource. BTW I am using Modern Objective-C syntax for the dictionary and arrays.
Having created a dictionary like that you could then simply implement your table view data source like so:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
// This gives the name of the category at the current section.
// It is then used as a key for the dictionary.
NSString *currentCategory = [[self.exerciseCategories objectAtIndex:section] exerciseCategoryName];
return [self.exercises[currentCategory] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ExercisePrototypeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSString *currentCategory = [[self.exerciseCategories objectAtIndex:indexPath.section] exerciseCategoryName];
MFTExercises *exercise = [self.exercises[currentCategory] objectAtIndex:indexPath.row];
cell.textLabel.text = exercise.exerciseName;
return cell;
}
Using a NSDictionary may or may not benefit your app but you don't have to create an array as instance variable for every body part you have. It may also be more easy to save a single dictionary to disk for persistence.

First of all, you should practice it with WWDC UITableView section. There are many source code that uses UITableView, UICollectionView and UIScrollView.
What you need in that code is you need to return section header for exerciseCategories, you only defined number of section in - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView this delegate function but you are returning all nil value for the section header at the moment.
- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
FNTExerciseCategories *category = [self.exerciseCategories objectAtIndex:section];
return category. exerciseCategoryName;
}
this will display your section. but you need to think about the structure of your data because right now you are not returning correct number for each section you are just returning [self.exercises count] for all section.
And to render the UINavigationController, you need to push the view rather than present view as modal.
[self.navigationController pushViewController:exerciseView animated:YES];

Related

UItableView with MagicalRecord huge data set

I have a table that stores some data. Let's say data is too big to load into memory all at once. I want to show this data in UItableView.
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [Item MR_numberOfEntities];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// How to get object for this row ???
return cell;
}
The only way i knew is to load all data into array with
NSArray *items = [Item MR_findAll];
But i don't want to do that. User will be shown first 10 rows, and why should i load all them from CoreData. Is there any way to fetch them one by one using MagicalRecord?
According to docs you need to init fetch request and also you may want to set the fetch offset depending on scroll progress.. but you will have to trace it manually. Here is a basic approach how it can be achieved.
PS. I haven't tested this code . I just wrote it in the text editor :). but it should work as you requested. e.g loading items with limit 10.
#property (nonatomic) int itemCount;
#property (nonatomic, strong) NSMutableArray * items
static const int FETCH_LIMIT = 10;
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _itemCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Classic start method
static NSString *cellIdentifier = #"MyCell";
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell)
{
cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MainMenuCellIdentifier];
}
MyData *data = [self.itemsArray objectAtIndex:indexPath.row];
// Do your cell customisation
// cell.titleLabel.text = data.title;
if (indexPath.row == _itemCount - 1)
{
[self loadMoreItems];
}
}
-(void)loadMoreItems{
int newOffset = _itemCount+FETCH_LIMIT; // Or _itemCount+FETCH_LIMIT+1 not tested yet
NSArray * newItems = [self requestWithOffset: newOffset];
if(!newItems || newItems.count == 0){
// Return nothing since All items have been fetched
return;
}
[ _items addObjectsFromArray:newItems ];
// Updating Item Count
_itemCount = _items.count;
// Updating TableView
[tableView reloadData];
}
-(void)viewDidLoad{
[super viewDidLoad];
_items = [self requestWithOffset: 0];
_itemCount = items.count;
}
-(NSArray*)requestWithOffset: (int)offset{
NSFetchRequest *itemRequest = [Item MR_requestAll];
[itemRequest setFetchLimit:FETCH_LIMIT]
[itemRequest setFetchOffset: offset]
NSArray *items = [Item MR_executeFetchRequest:itemRequest];
return items;
}
Hope you find it helpful :)

How to access objects inside an array object

I am creating an application for IOS and am struggling with accessing an object inside an array i have made for display on the table view cell.
This is the code i have used to add the object to the array every time the loop cycles through.
for (int i = 0; i < [parsedArray count]; i++) {
HPTBusStops *busStops = [[HPTBusStops alloc] init];
NSArray *informationArray = [parsedArray objectAtIndex:i];
busStops.busStopNumber = [informationArray objectAtIndex:0];
busStops.busStopName = [informationArray objectAtIndex:1];
busStops.latitude = [informationArray objectAtIndex:2];
busStops.longitude = [informationArray objectAtIndex:3];
[self.busStopsHolder addObject:busStops];
}
The HPTBusStops class is obviously custom, and later in the master view controller, i am tring to re-access these properties through the busStopsHolder array, when programming the cell, in this part:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
HPTBusStopsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"BusStopCell" forIndexPath:indexPath];
return cell;
}
I am honestly very unsure of how to access the busStops object's properties through the busStopHolder's array.
Any help would be appreciated
Thanks
Hamish
It looks to me like you might have an issue with scope...
You'll need to make "busStopsHolder" a #property of the class containing the for loop and instantiate that class as an instance variable in your Master View Controller.
in your class, say MyInfoClass.h:
#property (strong, nonatomic) NSMutableArray *busStopsHolder;
in MyInfoClass.m:
synthesize busStopsHolder;
Make sure you have initialized your busStopsHolder array in MyInfoClass...
(id) init {
busStopsHolder = [[NSMutableArray alloc] init];
}
Then in your master view controller .h:
#import "MyInfoClass.h"
#interface myMastserViewController : UIViewController {
MyInfoClass *infoClass;
}
Then...
- (void) viewDidLoad {
infoClass = [[MyInfoClass alloc] init];
[infoClass methodToLoadBusStops];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
HPTBusStopsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"BusStopCell" forIndexPath:indexPath];
HPTBusStop *busStop = [[infoClass busStopsHolder] objectAtIndex:indexPath.row];
[[cell textLabel] setText:[busStop busStopName]]
return cell;
}
An oversimplified way to do this is as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
HPTBusStopsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"BusStopCell" forIndexPath:indexPath];
HPTBusStops *busStops = yourSourceArray[indexPath.row];
cell.textLabel.text = busStops.name;
return cell;
}
If your tableView has one section, you can use the tableView's indexPath.row property to determine which index you're dealing with, use that as the index to access the relevant object in your source array, and then customize the cell based on the specific object at that index. In the example code I just assumed there was a name property on the busStops object for example purposes.
Make sure in your numberOfRowsInSection method you set the number of rows as the number of objects in your source array, whatever that is.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return yourSourceArray.count;
}

Populate tableview from NSDictionary

I have an NSDictionary received from a json request that looks like this:
RESULT : (
{
Id1 = 138;
lat = "45.5292910";
long = "-73.6241500";
order = "2343YY3"
},
{
Id1 = 137;
lat = "45.5292910";
long = "-73.6241500";
order = "2343YY3"
}, etc.
I want to display it in a TableView (CellforRowAtIndexPath), so I obtain the data as NSArray. The method seems inefficient as each key Id1, lat, long, etc is created as an NSArray so that I can display them each with: [self.data1 objectAtIndex:indexPath.row]; [self.data2 objectAtIndex:indexPath.row], etc.
How can I achieve the same thing without creating and using 4 NSArrays? Can I use a single NSArray or the NSMutableDictionary which stores the data?
UPDATED:
When the TableView loads, it is initially empty but I have a button on that same VC that loads a modal view of a form. When I load the form and then dismiss it returning to the TableView, the data is LOADED! Could you suggest what I am missing?
Yes you can use a single array. The trick is to create an array with each array entry holding a dictionary. Then you query the array to populate your tableview.
E.g.: If your array is a property called tableData and you have custom tableview cell called CustomCell then your code might look something like the following:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [self.tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CustomCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
cell.latitude.text = [[self.tableData objectAtIndex:indexPath.row] objectForKey: #"lat"];
cell.longitude.text = [[self.tableData objectAtIndex:indexPath.row] objectForKey:#"long"];
// continue configuration etc..
return cell;
}
Similarly, if you have multiple sections in your tableview then you will construct an array of arrays, with each sub-array containing the dictionaries for that section. The code to populate the tableview would look something similar to the following:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return [self.tableData count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [[self.tableData objectAtIndex:section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CustomCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
cell.latitude.text = [[[self.tableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey: #"lat"];
cell.longitude.text = [[[self.tableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:#"long"];
// continue configuration etc..
return cell;
}
TL;DR; Take your dictionaries created from your JSON data and put them in an array. Then query the array to populate the tableview.
You can do as follows:
// main_data = Store your JSON array as "array of dictionaries"
Then in cellForRowAtIndexPath do as follows:
NSDictionary *obj = [main_data objectAtIndex: indexPath.row];
// Access values as follows:
[obj objectForKey: #"Id1"]
[obj objectForKey: #"lat"]
...
...

Advice on creating table with dynamic data in IOS

I am trying to create a table with dynamic data and I'm kind of stuck. Here is how my data is structured :
NSMutableArray *bigArray;
bigArray has many NSDictionary items.
each items has only one entry.
sectionName is the key, NSMutableArray is the value.
There are many objects in the value NSMutableArray.
I tried to explain this as simple as I could, here is the part where I'm stuck.
//easy
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [bigArray count];
}
//medium
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [[[[bigArray objectAtIndex:section] allValues] objectAtIndex:0] count];
}
I can't figure out this part how to implement this method based on my current data structure :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:#"MyCell"];
MyObject *obj = //Need this part
cell.textLabel.text = obj.name;
return cell;
}
Simply put, I'm trying to insert dynamic sections with dynamic data. I'm looking for advice from more experienced developers, how would you tackle this?
Assuming I understood well how your data is structured, here's how I would do it:
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyCell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MyCell"];
}
//this will get you the dictionary for the section being filled
NSDictionary *item = [bigArray objectAtIndex:indexPath.section];
// then the array of object for the section
NSMutableArray *mutableArray = [item objectForKey:#"sectionName"];
//you then take the object for the row
MyObject *obj = [mutableArray objectAtIndex:indexPath.row];
cell.textLabel.text = obj.name;
return cell;
}
Don't forget to set the reuse identifier for the cell prototype in the attributes inspector

UITableView Indexing

I have an indexed table view that organizes cities in a state by their first letter. What I have working is an NSMutableDictionary is created with the keys of A,B,C,etc. and the corresponding cities are added to their respective arrays. ex:
Y = (
Yatesboro,
Yeagertown,
York,
"York Haven",
"York New Salem",
"York Springs",
Youngstown,
Youngsville,
Youngwood,
Yukon
);
Z = (
Zelienople,
Zieglerville,
"Zion Grove",
Zionhill,
Zionsville,
Zullinger
);
now, my table view loads with the correct number of sections, and rows within the sections and the indexing control works fine with this:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [cities count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if([searchArray count]==0)
return #"";
return [searchArray objectAtIndex:section];
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[cities objectForKey:[searchArray objectAtIndex:section]] count];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
NSLog([NSString stringWithFormat:#"clicked index : %i",index]);
if (index == 0) {
[tableView scrollRectToVisible:[[tableView tableHeaderView] bounds] animated:NO];
return -1;
}
return index;
}
My issue is now populating the text of the table cell with the text for each section...Any thoughts on how I can grab this info?
the cellForRowAtIndexPath gets a parameter of type NSIndexPath passed which contains both the required row and section. See NSIndexPath UIKit Additions for more details.
With that being said, this might work in your particular case:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier] autorelease];
}
NSString *letter = [searchArray objectAtIndex:indexPath.section];
NSArray *city = [cities objectForKey:letter];
cell.text = [city objectAtIndex:indexPath.row];
return cell;
}
Not sure if I got it right (haven't tried on a compiler), but you may get the general idea by now :)

Resources