Multidimensional array object for table view cell selected - objective-c

I have a dictionary of arrays, and each of these arrays has a number of arrays itself. Its a multidimensional array in a dictionary.
When I click on a UItable row, I push the view to another class, however I want to push along with the view, the array whose object key is the same as the row name that was clicked.
My code is as follows
(The class that does the pushing)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic -- create and push a new view controller
if(dvController == nil)
dvController = [self.storyboard instantiateViewControllerWithIdentifier:#"FoodCategoryView"];
//NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//NSMutableDictionary *keysAndObjects = [defaults objectForKey:#"keysAndObjects"];
Food *foodObj;
/*for (id key in [keysAndObjects allKeys]) {
NSArray *foodArray = [keysAndObjects objectForKey:key];
foodObj = [foodArray objectAtIndex:indexPath.row];
}*/
/*for (id key in [keysAndObjects allKeys]) {
NSArray *foodArray = [keysAndObjects objectForKey:key];
for (Food *food in foodArray) {
// do stuff with Food object
//NSLog(#"%#", food.foodName);
}
}*/
NSMutableArray *objects2 = [[NSMutableArray alloc] init];
NSMutableArray *objects1 = [[NSMutableArray alloc] init];
objects1 = [objects objectAtIndex:indexPath.row];
objects2 = [objects1 objectAtIndex:indexPath.row];
foodObj = objects2;
//NSLog(#"Object %#", [objects objectAtIndex:indexPath.row]);
NSLog(#"foodObj %#", foodObj);
//Get the detail view data if it does not exists.
//We only load the data we initially want and keep on loading as we need.
//[foodObj hydrateDetailViewData];
dvController.foodObj = foodObj;
[self.navigationController pushViewController:dvController animated:YES];
}
(the class that the view is pushed to)
- (UITableViewCell *)tableView:(UITableView *)tblView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier];
}
/*for (Food *food in foodObj) {
// do stuff with Food object
NSLog(#"%#", food.foodName);
cell.text = food.foodName;
}*/
//Food *food = [foodObj objectAtIndex:indexPath.row];
//cell.text = [foodObj objectAtIndex:indexPath.row];
cell.text = foodObj.foodName;
NSLog(#"%#", foodObj.foodName);
return cell;
}
As you can see there are lots of comments as I have tried lots of different ways to do it myself.

Related

Why my tableView did not display anything

i want select over 50 in the first section,and others in the second section ,but there is no value display in tableView ,and when i use NSlog("%#",self.over50) ,there is no reaction
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"UITableViewCell" ];
NSArray* items = [[BNRItemStore shareStore] allItems];
self.itemsUnder50 = [[NSMutableArray alloc] init];
self.itemsOver50 = [[NSMutableArray alloc] init];
for (BNRItem *item in items) {
if (indexPath.section ==0) {
[self.itemsOver50 addObject:item];
cell.textLabel.text = [self.itemsOver50[indexPath.row] description];
NSLog(#"%#",self.itemsUnder50);
}
else if(indexPath.section == 1){
[self.itemsUnder50 addObject:item];
cell.textLabel.text = [self.itemsUnder50[indexPath.row] description];
}
}
return cell;
}
connect the datasource and delegate of the tableview to the viewController

How to allow duplicate entries in a table view

I want to be able to load a playlist with duplicate song titles into a table view. However when the playlist is selected the table view automatically removes the duplicates? How do I prevent this and allow the duplicates to show in the table view?
This is the code I am using:
- (void) updatePlayerQueueWithMediaCollection: (MPMediaItemCollection *) mediaItemCollection
{
// Configure the music player, but only if the user chose at least one song to play
if (mediaItemCollection)
{
if (_userMediaItemCollection == nil)
{
self.userMediaItemCollection = mediaItemCollection;
[[GVMusicPlayerController sharedInstance ] setQueueWithItemCollection: _userMediaItemCollection];
if (array == nil)
{
[self savePlaylist:[MPMediaItemCollection collectionWithItems: self.userMediaItemCollection.items]];
}
else
{
[array addObjectsFromArray:self.userMediaItemCollection.items];
[self savePlaylist:[MPMediaItemCollection collectionWithItems: array]];
}
}
else
{
NSMutableArray *currentSongsList= [[_userMediaItemCollection items] mutableCopy];
NSArray *nowSelectedSongsList = [mediaItemCollection items];
[currentSongsList addObjectsFromArray:nowSelectedSongsList];
self.userMediaItemCollection = [MPMediaItemCollection collectionWithItems:(NSArray *) currentSongsList];
// Apply the new media item collection as a playback queue for the music player.
[[GVMusicPlayerController sharedInstance ] setQueueWithItemCollection: _userMediaItemCollection];
[[GVMusicPlayerController sharedInstance] pause];
//save playlist
[array addObjectsFromArray:_userMediaItemCollection.items];
[self savePlaylist:[MPMediaItemCollection collectionWithItems: array]];
}
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//this method is called to fill out table with data
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"Cell"];
}
// populate the cell from array
anItem = nil;
anItem = [array objectAtIndex:indexPath.row];
// Configure the cell
cell.textLabel.text = [anItem valueForProperty:MPMediaItemPropertyTitle];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
return cell;
}

How to add multiple Objects to Array - Objective C / iOS

I'm new to programming in Objective C
Here is my Dilemma: I'm pulling in a JSON file from the web and I'm able to display one of the elements (currDate) to my tableView but now I want to display more. From the code below I would I get it to display both currDate and prevDate
The logic needs to be changed here:
for (NSDictionary *diction in arrayOfEntry) {
NSString *currDate = [diction objectForKey:#"Current Date"];
a = currDate;
NSString *prevDate = [diction objectForKey:#"Previous Date"];
b = prevDate;
[array addObject:a];
}
[[self myTableView]reloadData];
I'm not sure if I need to change anything here but I'm attaching it to show how I'm displaying the array to my viewTable:
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(!cell)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [array objectAtIndex:indexPath.row];
//cell.textLabel.text = [array objectsAtIndexes:indexPath.row];
return cell;
}
just add another line:
[array addObject:a];
[array addObject:b];
make arrayOfEntry global. in .h file
NSArray *arrayOfEntry;
In numberOfRowsInSection
[arrayOfEntry count]
In tableView: cellForRowAtIndexPath
NSString *currDate = [[arrayOfEntry objectAtIndex:indexPath.row] objectForKey:#"Current Date"]
NSString *prevDate = [[arrayOfEntry objectAtIndex:indexPath.row] objectForKey:#"Previous Date"]
cell.textLabel.text = [NSString stringWithFormat:#"%# %#", currDate, prevDate];
To add multiple elements to an Array in objective c you need to use:
NSMutableArray *newArr = [NSMutableArray new];
Then:
[newArr addObject:dict1];
If you want, you can then set your NSArray you were using to the NSMutuableArray after the addition of objects is complete.

My UITableView shows the same item on every row

I have a UITableView which I want to populate with details from an array of objects. The tableview shows the same item on every line (the correct number of lines though!) I know this must be an easy one - but I can't see where I've gone wrong:
Code snippet of view that initializes the table data:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"Show Tank List"])
{
NSURL *myUrl = [[NSURL alloc]initWithString:#"http://localhost/~stephen-hill9/index.php"];
NSData *data = [[NSData alloc] initWithContentsOfURL:myUrl];
NSError *error;
NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
int i;
NSMutableArray *tanksList;
tank *thisTank = [[tank alloc] init];
tanksList = [[NSMutableArray alloc] init];
for (i=0; i<json.count; i++) {
NSDictionary *bodyDictionary = [json objectAtIndex:i];
thisTank.tankNumber = [bodyDictionary objectForKey:#"ID"];
thisTank.tankProduct = [bodyDictionary objectForKey:#"Product_Desc"];
thisTank.tankPumpableVolume = [bodyDictionary objectForKey:#"Pumpable"];
[tanksList addObject:thisTank];
}
[segue.destinationViewController setTanks:tanksList];
}
}
...and the code that loads the table in the next view...
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;//keep this section in case we do need to add sections in the future.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.tanks count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Tank List Table Cell";
UITableViewCell *cell = [self.tankTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero];
}
tank *thisTank = [self.tanks objectAtIndex:indexPath.row];
cell.textLabel.text = thisTank.tankNumber;
return cell;
}
Move this:
tank *thisTank = [[tank alloc] init];
Inside your for loop. You're updating the same object over and over again.
Also, you're initialising the cell wrong - use the designated initialiser, and pass the reuse identifier in, otherwise you will create new cells all the time:
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
And you really should follow objective-c naming conventions. Classes begin with upper case letters, everything else begins with a lower case letter. It makes your code much easier to read, for other people anyway.
reload the table every time!!!
[self.tableView reloadData];

Cocoa Touch UITableView Data

I am working for the first time in objective c and have come across an issue that I have not seen an answer for.
I am loading a set of data from a JSON data set and using it to populate a UITableView within a UITableViewController.
First when the view is loaded (viewDidLoad) I populate the array with the JSON data from a URL.
Next the data loads as it should. numberOfRowsInSection shows that there are 30 results in the array which is correct.
However The Iphone loads the entire set three times into the tableview.
Here is some code from the controller for that view:(Twitter is being used as an example and is not the actual data set I use)
- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
//results = [[NSMutableArray alloc] init];
self.navigationItem.title=#"public_timeline";
self.tableView.allowsSelection = NO;
NSString *url = [[NSString alloc] init];
url = [[NSString alloc] initWithFormat:#"http://twitter.com/statuses/%s.json",#"public_timeline"];
if ([results count] == 0) {
[self parseJSON:url];
}
}
Here is the parseJSON (actual parse is done with the Cocoa JSON framework
-(void) parseJSON:(NSString *)URL{
NSURL *JSONURL = [NSURL URLWithString:URL];
NSData *responseData = [[NSData alloc] initWithContentsOfURL:JSONURL];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
results = [[NSMutableArray alloc] initWithArray:[responseString JSONValue]];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [results count];
}
then the cell's output
- (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];
// Set up the cell...
}
NSDictionary *cdict = [results objectAtIndex:indexPath.row];
cell.textLabel.text = [cdict valueForKey:#"text"];
return cell;
}
I am not sure if what I am doing is the best way to do this, so if someone could help me out that would be great.
Check the numberOfSectionsInTableView Method and change the return Value to 1
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}