TableView to detailTableView - one step behind - iphone

When I connect the my tableView to a detailtableView I get the the "error" that the detailtableView is one step behind. For example when clicking the 2nd cell in the mastertableView it show the 1st cell detailInformation. Hope you understand my problem.
See my .m.
#import "GuideTableViewController.h"
#import "GuideDetailTableViewController.h"
#interface GuideTableViewController (){
NSArray *guide;
}
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#end
#implementation GuideTableViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
//JSONmetod
- (void) loadJSON{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//code
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://dl.dropbox.com/u/100670549/test.json"]];
NSError *error;
if (data)
{
guide = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
for (NSDictionary *dictionary in guide){
NSLog([dictionary description]);
}
}else
{
NSLog(#"Could not load data");
}
dispatch_sync(dispatch_get_main_queue(), ^{
// code
[self.tableView reloadData];
});
});
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//Anropa json
[self loadJSON];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//TableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return guide.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
NSDictionary *dict = [guide objectAtIndex:indexPath.row];
cell.textLabel.text = [dict valueForKey:#"title"];
return cell;
}
//Till detailView
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:#"showStay"]){
GuideDetailTableViewController *tvc = [segue destinationViewController];
NSIndexPath *index = sender;
NSDictionary *dict = [guide objectAtIndex:index.row];
tvc.stay = dict;
}
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
[self performSegueWithIdentifier:#"showStay" sender:indexPath];
}
#end
Thanks in advance!

you used didDeselectRowAtIndexPath instead of didSelectRowAtIndexPath Delegate method, common autocomplete mistake.

Related

How to Connect two tables using NSDictionary?

In my iphone design, there are two table views added.
One table view is for displaying the MenuList for hotels using NsDictionary(Like Veg. NonVeg, Beverages..) and the other table view is for displaying the ListItems(Like In veg, i will Have Paneer,Rotti..) . When ever a menuList cell is selected the files inside the selected list needs to to be displayed in the other table view(ListIems).
My problem is
I am confused about
I want to use NsDictionary Alone in this two table . Can anyone give me a simple code for this. i am confused and am a fresher. Thanks In advance if someone teaches me. Please help. iam using xcode5
#interface TableViewController ()
#end
#implementation TableViewController
#synthesize menuDict ;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
menuName = [NSArray arrayWithObjects:#"Veg", #"NonVeg", #"Beverages", nil];
menuId = [NSArray arrayWithObjects:#"1", #"2", #"3", nil];
self.menuDict = [NSDictionary dictionaryWithObjects:menuName
forKeys:menuId];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[self.menuDict allKeys] count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *unifiedID = #"TableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:unifiedID];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:unifiedID];
}
for (id key in self.menuDict) {
NSLog(#"key: %#, value: %#", key, [self.menuDict objectForKey:key]);
}
NSString *key = [self.menuDict allKeys][indexPath.row];
NSString *menuNameString = self.menuDict[key];
NSString *menuIdString = key;
cell.textLabel.text = menuNameString;
cell.detailTextLabel.text = menuIdString;
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([[segue identifier] isEqualToString:#"ShowDetails"])
{
NSDictionary *vvegDict = [[NSDictionary alloc]initWithObjectsAndKeys:#"1",#"Rotti" , #"2", #"Panner", nil] ;
DetailTableViewController *tvc = segue.destinationViewController ;
tvc.vegDict =vvegDict ;
}
}
second table :
// Is this right to declare the lists here same as my first table. Please help me in this one.
#interface DetailTableViewController ()
#end
#implementation DetailTableViewController
#synthesize vegName,vegId ;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
vegName = [NSArray arrayWithObjects:#"Rotti", #"Panneer", #"Chappathi", nil];
vegId = [NSArray arrayWithObjects:#"1", #"2", #"3", nil];
self.vegDict = [NSDictionary dictionaryWithObjects:vegName
forKeys:vegId];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1 ;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[self.vegDict allKeys]count] ;
return 1 ;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *unifiedID = #"aCellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:unifiedID];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:unifiedID];
}
for (id key in self.vegDict) {
NSLog(#"key: %#, value: %#", key, [self.vegDict objectForKey:key]);
}
NSString *key = [self.vegDict allKeys][indexPath.row];
NSString *vegNameString = self.vegDict[key];
NSString *vegIdString = key;
cell.textLabel.text = vegNameString;
cell.detailTextLabel.text = vegIdString;
return cell;
}
If you are using Segues to go from one uitableviewcontroller to other then you can use
-prepareForSegue:sender:
in this method you can set an NSDictionary property in the destination view controller. You can get the the destination view controller from the the sender argument.

prepareforSegue tableViewCell to different detailTableViews

I´m having a tableView in a viewController with an array (3 labelTitles to 3 different detailViews). My problem is in the prepareForSegue-method, I dont really know how to call the detailViews. I use the correct segue identifiers names.
"master".m:
#import "GuideTableViewController.h"
#import "GuideDetailTableViewController.h"
#import "GuideDetailTableViewController2.h"
#import "GuideDetailTableViewController3.h"
#import <QuartzCore/QuartzCore.h>
#import "customImageCell.h"
#interface GuideTableViewController (){
NSMutableData *weatherResponseData;
NSArray *titleLabels;
NSArray *imagesLeft;
}
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property (weak, nonatomic) IBOutlet UIImageView *imgHeader;
#property (weak, nonatomic) IBOutlet UIImageView *ImgTitle;
#property (weak, nonatomic) IBOutlet UIImageView *ImgWeather;
#property (weak, nonatomic) IBOutlet UIButton *btnMap;
#property (weak, nonatomic) IBOutlet UILabel *LabelWeather;
#property (weak, nonatomic) IBOutlet UILabel *LabelWeather2;
#end
#implementation GuideTableViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
//Weather method
- (void) loadWeather{
NSURLRequest *theRequest = [NSURLRequest requestWithURL:
[NSURL URLWithString:#"http://api.wunderground.com/api/3919480da5014c98/conditions/q/BR/Sao_Sebastiao.json"]];
NSURLConnection *theConnection=[[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
if(theConnection){
weatherResponseData = [[NSMutableData alloc] init];
} else {
NSLog(#"failed");
}
}
//Delegates for WeatherData
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[weatherResponseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[weatherResponseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSString *msg = [NSString stringWithFormat:#"Failed: %#", [error description]];
NSLog(#"%#",msg);
}
//All the data was loaded, let's see what we've got...
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:weatherResponseData options:NSJSONReadingMutableLeaves error:&myError];
NSArray *results = [res objectForKey:#"current_observation"];
NSString *cur = [results valueForKey:#"weather"];
NSString *tmp = [results valueForKey:#"temperature_string"];
NSString *wind = [results valueForKey:#"wind_string"];
NSLog(#"Current conditions: %#, %#º, %#", cur, tmp, wind);
self.LabelWeather.text = cur;
self.LabelWeather2.text = tmp;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self loadWeather];
titleLabels = [NSArray arrayWithObjects:#"Where to stay",#"Where to eat",#"What to do",nil];
imagesLeft = [NSArray arrayWithObjects:#"btn_Stay.png", #"btn_Eat.png", #"btn_Todo.png", nil];
//set background
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background.jpg"]];
//rounded corners
[self.tableView.layer setCornerRadius:9.0];
[self.ImgWeather.layer setCornerRadius:9.0];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//TableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return titleLabels.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
customImageCell *cell = (customImageCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSString *cellLabel = [titleLabels objectAtIndex:indexPath.row];
cell.titleLabel.text = cellLabel;
NSString *cellImage = [imagesLeft objectAtIndex:indexPath.row];
UIImage *cellIcon = [UIImage imageNamed:cellImage];
cell.imageLeft.image = cellIcon;
return cell;
}
//To detailTableViewController
- (void)tableView:(UITableView *)tableView didselectRowAtIndexPath:(NSIndexPath *)indexPath{
if(indexPath.row == 0){
[self performSegueWithIdentifier:#"stay" sender:self];
}else if(indexPath.row ==1 ){
[self performSegueWithIdentifier:#"eat" sender:self];
}else{
[self performSegueWithIdentifier:#"todo" sender:self];
}
}
- (void) viewWillAppear:(BOOL)animated{
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.tableView.indexPathForSelectedRow];
[cell setSelected:NO];
//Hide navbar
[self.navigationController setNavigationBarHidden:YES];
}
//Show navbar in detailView
-(void)viewWillDisappear:(BOOL)animated{
[self.navigationController setNavigationBarHidden:NO];
}
#end
change didselectRow
- (void)tableView:(UITableView *)tableView didselectRowAtIndexPath:(NSIndexPath *)indexPath{
if(indexPath.row == 0){
[self performSegueWithIdentifier:#"stay" sender:self];
}else if(indexPath.row ==1 ){
[self performSegueWithIdentifier:#"eat" sender:self];
}else{
[self performSegueWithIdentifier:#"todo" sender:self];
}
}

DidSelectRowAtIndexPath not being called

I have 3 different detailTableViews that my cells in my masterTableView will call when touched.
Please see my master.m file:
#import "GuideTableViewController.h"
#import "GuideDetailTableViewController.h"
#import "GuideDetailTableViewController2.h"
#import "GuideDetailTableViewController3.h"
#import <QuartzCore/QuartzCore.h>
#interface GuideTableViewController (){
NSMutableData *weatherResponseData;
NSArray *headGuide;
NSArray *leftImages;
}
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property (weak, nonatomic) IBOutlet UIImageView *imgHeader;
#property (weak, nonatomic) IBOutlet UIImageView *ImgTitle;
#property (weak, nonatomic) IBOutlet UIImageView *ImgWeather;
#property (weak, nonatomic) IBOutlet UIButton *btnMap;
#property (weak, nonatomic) IBOutlet UILabel *LabelWeather;
#property (weak, nonatomic) IBOutlet UILabel *LabelWeather2;
#end
#implementation GuideTableViewController
//Weather method
- (void) loadWeather{
NSURLRequest *theRequest = [NSURLRequest requestWithURL:
[NSURL URLWithString:#"http://api.wunderground.com/api/3919480da5014c98/conditions/q/BR/Sao_Sebastiao .json"]];
NSURLConnection *theConnection=[[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
if(theConnection){
weatherResponseData = [[NSMutableData alloc] init];
} else {
NSLog(#"failed");
}
}
//Delegates for WeatherData
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[weatherResponseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[weatherResponseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSString *msg = [NSString stringWithFormat:#"Failed: %#", [error description]];
NSLog(#"%#",msg);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:weatherResponseData options:NSJSONReadingMutableLeaves error:&myError];
NSArray *results = [res objectForKey:#"current_observation"];
NSString *cur = [results valueForKey:#"weather"];
NSString *tmp = [results valueForKey:#"temperature_string"];
NSString *wind = [results valueForKey:#"wind_string"];
NSLog(#"Current conditions: %#, %#º, %#", cur, tmp, wind);
self.LabelWeather.text = cur;
self.LabelWeather2.text = tmp;
}
//JSONmethod
- (void) loadJSON{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//code
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://dl.dropbox.com/u/100670549/guide.json"]];
NSError *error;
if (data)
{
headGuide = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
for (NSDictionary *dictionary in headGuide){
// NSLog([dictionary description]);
}
}else
{
NSLog(#"Could not load data");
}
dispatch_sync(dispatch_get_main_queue(), ^{
// code
[self.tableView reloadData];
});
});
}
//Load
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self loadJSON];
[self loadWeather];
leftImages = [NSArray arrayWithObjects:#"btn_Stay.png", #"btn_Eat.png", #"btn_Todo.png", nil];
// set background
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background.jpg"]];
// rounded corners
[self.tableView.layer setCornerRadius:9.0];
[self.ImgWeather.layer setCornerRadius:9.0];
}
#pragma mark - Table view data source
- (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 headGuide.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
NSArray *dict = [headGuide objectAtIndex:indexPath.row];
cell.textLabel.text = [dict valueForKey:#"title"];
NSString *cellImage = [leftImages objectAtIndex:indexPath.row];
UIImage *cellIcon = [UIImage imageNamed:cellImage];
cell.imageView.image = cellIcon;
return cell;
}
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:#"whereStay"]){
GuideDetailTableViewController *vc = [segue destinationViewController];
NSIndexPath *index = sender;
NSDictionary *dict = [headGuide objectAtIndex:index.row];
vc.stayGuide = dict;
}
else if ([segue.identifier isEqualToString:#"whereEat"]){
GuideDetailTableViewController2 *vc1 = [segue destinationViewController];
NSIndexPath *index = sender;
NSDictionary *dict = [headGuide objectAtIndex:index.row];
vc1.eatGuide = dict;
}
else if ([segue.identifier isEqualToString:#"whatTodo"]){
GuideDetailTableViewController3 *vc2 = [segue destinationViewController];
NSIndexPath *index = sender;
NSDictionary *dict = [headGuide objectAtIndex:index.row];
vc2.todoGuide = dict;
}
}
#pragma mark - tableView delegate
- (void)tableView:(UITableView *)tableView didselectRowAtIndexPath:(NSIndexPath *)indexPath{
if(indexPath.row == 0){
[self performSegueWithIdentifier:#"whereStay" sender:indexPath];
}else if(indexPath.row ==1 ){
[self performSegueWithIdentifier:#"whereEat" sender:indexPath];
}else{
[self performSegueWithIdentifier:#"whatTodo" sender:indexPath];
}
[tableView setAllowsSelection:YES];
}
#end
Your method signature is also not properly capitalized:
- (void)tableView:(UITableView *)tableView didselectRowAtIndexPath:(NSIndexPath *)indexPath{
should be
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
Method names are case sensitive.
Additionally, make sure you're setting the tableView's delegate with
self.tableView.delegate = self;
It doesn't look like you're setting this object as the delegate of your table view. In your -viewDidLoad method, you should call [[self tableView] setDelegate:self];
Where is your protocol for tableview delegate and datasource?
#interface GuideTableViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>
{
//Attributes...
IBOutlet UITableView *tableView;
}
in viewDidLoad, you should set the delegates:
tableView.delegate = self;
tableView.dataSource = self;
you could also set delegates in xib files...
So your delegates Methods should works... Check out with apple docs about tableview:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableView_Class/Reference/Reference.html

Putting my JSON into a tableView

what i'm currently trying to do is get my json information (twitter user timeline) and stick it into a table, everything about it json works, but when it comes to adding the information to the tableView it doesn't do anything about it, Here is my code :
#import "FirstViewController.h"
#import <Twitter/Twitter.h>
#import <Accounts/Accounts.h>
#interface FirstViewController ()
- (void)fetchData;
#end
#implementation FirstViewController
#synthesize timelineTwiter = _timelineTwiter;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"First", #"First");
self.tabBarItem.image = [UIImage imageNamed:#"first"];
}
return self;
}
-(void)fetchData {
ACAccountStore *store = [[ACAccountStore alloc] init];
ACAccountType *twitterAccountType =
[store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[store requestAccessToAccountsWithType:twitterAccountType
withCompletionHandler:^(BOOL granted, NSError *error) {
if (!granted) {
NSLog(#"User rejected access to his account.");
}
else {
NSArray *twitterAccounts =
[store accountsWithAccountType:twitterAccountType];
if ([twitterAccounts count] > 0) {
ACAccount *account = [twitterAccounts objectAtIndex:0];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:#"1" forKey:#"include_entities"];
NSURL *url =
[NSURL
URLWithString:#"http://api.twitter.com/1/statuses/home_timeline.json"];
TWRequest *request =
[[TWRequest alloc] initWithURL:url
parameters:params
requestMethod:TWRequestMethodGET];
[request setAccount:account];
[request performRequestWithHandler:
^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (!responseData) {
NSLog(#"%#", error);
}
else {
NSError *jsonError;
NSArray *timeline = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&jsonError];
self.timelineTwiter = timeline;
if (timeline) {
NSDictionary* tweets0 = [timeline objectAtIndex:0];
NSLog(#"%#", [tweets0 objectForKey:#"text"]);
NSLog(#"%#", [[tweets0 objectForKey:#"user"] objectForKey:#"screen_name"]);
NSDictionary* tweets1 = [timeline objectAtIndex:1];
NSLog(#"%#", [tweets1 objectForKey:#"text"]);
NSLog(#"%#", [[tweets1 objectForKey:#"user"] objectForKey:#"screen_name"]);
NSDictionary* tweets2 = [timeline objectAtIndex:2];
NSLog(#"%#", [tweets2 objectForKey:#"text"]);
NSLog(#"%#", [[tweets2 objectForKey:#"user"] objectForKey:#"screen_name"]);
}
else {
NSLog(#"%#", jsonError);
}
}
}];
}
}
}];
}
-(IBAction)refreshTimeline:(id)sender {
[self fetchData];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.timelineTwiter count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
id userTimeline = [self.timelineTwiter objectAtIndex:[indexPath row]];
cell.textLabel.text = [userTimeline objectForKey:#"text"];
cell.detailTextLabel.text = [userTimeline valueForKeyPath:#"user.name"];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchData];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewWillAppear:(BOOL)animated
{
[self fetchData];
[super viewWillAppear:animated];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#end
but it never loads the data into the table view, any help?
Side note:
I am using it with interface builder.
& Ideally i'd like to make a custom cell so i could work out the layout each cell, so if you know of any good sites which will show how to do that, that'd also be a big hand.
you have to return at least one section to the table at a minimum. right now you are return zero sections.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
You missed the reloadData at the end of your fetchData implementation.

UITableView gives empty table, does not load data

Everything works fine when the view that holds my table is the main (first) view.
However, when it's not the first view and I switch into that view, my table does not load data and I get an empty table.
Using NSLog I can tell that the program is not invoking numberOfRowsInSection and cellForRowAtIndexPath.
I have <UITableViewDataSource, UITableViewDelegate>, IBOutlet UITableview *tableView all declared. They are also connected in the InterfaceBuilder.
I tried using viewWillAppear and [tableView reloadData] but that did not help.
I'm new to iPhone development and your help is appreciated!
UPDATE:
I tried [tableView reloadData] but nothing happened.
I'm not releasing tableView anywhere but dealloc.
Here is some code:
appDelegate
//
// tpbAppDelegate.m
// tpb
#import "listController.h"
#import "tpbAppDelegate.h"
#import "tpbViewController.h"
#implementation tpbAppDelegate
#synthesize window;
#synthesize viewController;
#synthesize navController;
#synthesize toolbar;
#synthesize btnMyLoc;
#synthesize places; //array that holds data from the XML file
- (void)applicationDidFinishLaunching:(UIApplication *)application {
//add places into an array that can be used by other views (Table)
rssList = [[NSMutableArray alloc] initWithCapacity:1];
NSString *paths = [[NSBundle mainBundle] resourcePath];
NSString *xmlFile = [paths stringByAppendingPathComponent:#"tourplay.xml"];
NSURL *xmlURL = [NSURL fileURLWithPath:xmlFile isDirectory:NO];
NSLog(#"DATA URL: %#", xmlURL);
NSXMLParser *firstParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
[firstParser setDelegate:self];
[firstParser parse];
// Resize window for toolbar:
CGRect frame = viewController.view.frame;
frame.size.height -= toolbar.frame.size.height;
viewController.view.frame = frame;
//[window addSubview:viewController.view];
navController.viewControllers = [NSArray arrayWithObject:viewController];
navController.view.frame = frame;
[window addSubview:navController.view];
[window makeKeyAndVisible];
}
- (IBAction)showList:(id)sender{
//Switch to table view on segment control change
UISegmentedControl *segmentControl = (UISegmentedControl *)sender;
NSString *curSelection = [NSString stringWithFormat:#"%d", [segmentControl selectedSegmentIndex]];
//[segmentControl titleForSegmentAtIndex: [segmentControl selectedSegmentIndex]]];
NSLog(#"pressed button %#", curSelection);
if ([curSelection isEqualToString:#"1"]){
NSLog(#"TABLE SELECTED");
listController *listTable = [[listController alloc] init];
[navController pushViewController:listTable animated:YES]; //SWITCH TO TABLE VIEW (listController)
} else {
tpbViewController *tpb = [[tpbViewController alloc] init];
NSLog(#"MAP SELECTED");
[navController pushViewController:tpb animated:YES];
}
}
#pragma mark Praser Methods
//Parse XML into an array
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
//NSLog(#"Started parsing");
if ([elementName compare:#"tour_point"] == NSOrderedSame) {
[self.places addObject:[[NSDictionary alloc] initWithObjectsAndKeys:
//[attributeDict objectForKey:#"tour_point_id"],#"tour_point_id",
[attributeDict objectForKey:#"name"],#"name",
[attributeDict objectForKey:#"tour_html"],#"tour_html",
[attributeDict objectForKey:#"audio_src"],#"audio_src",
nil]];
} else if ([elementName compare:#"title"] == NSOrderedSame) {
titlename = (NSString *)[attributeDict objectForKey:#"titlename"];
NSLog(#"Done parsing %# points", titlename);
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
NSLog(#"Parser end");
[parser release];
}
- (void)dealloc {
[viewController release];
[rssList release];
[places release];
[toolbar release];
[window release];
[super dealloc];
}
#end
listController.h - table class
#import <UIKit/UIKit.h>
#interface listController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
UITableView *tableView;
NSMutableArray *places;
NSString *titlename;
}
#property (nonatomic, retain) IBOutlet UITableView *tableView;
#end
listController.m - table implemenation
//
// listController.m
// tpb
//
//
#import "listController.h"
#import "tpbAppDelegate.h"
#implementation listController
#synthesize tableView;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
//- (void)viewWillAppear {
tpbAppDelegate *delegate = (tpbAppDelegate *)[[UIApplication sharedApplication] delegate];
places = delegate.places;
NSLog(#"Loaded table view");
[super viewDidLoad];
// [tableView reloadSectionIndexTitles];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tv {
NSLog(#"Number of secions");
return 1;
}
- (NSInteger)tableView:(UITableView *)tv numberOfRowsInSection:(NSInteger)section {
NSLog(#"GETTING COUNT");
return [places count];
}
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"Assigning Cells");
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
if (nil == cell) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [[places objectAtIndex:indexPath.row] objectForKey:#"name"];
//NSLog(#"count %#", [[places objectAtIndex:indexPath.row] objectForKey:#"name"]);
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"ROW clicked");
[tv deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
NSLog(#"Unloaded tableview");
}
- (void)dealloc {
[tableView release];
[places release];
[super dealloc];
}
#end
-- So far, I know that viewDidLoad loads, but the table meathods such as cellRowAtIndexPath are not invoked.
This problem happens when you do not link the datasource and delegate of table view to the file's owner in the interface builder. Cross check once again in the interface builder see the connections for datasource and delegate of tableview are properly made with files owner and you have not mistakenly linked them with view.
Besides tell one thing more if
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
is getting called. If it is then you have passed 0 in this. Well a '0' is not acceptable from iphone-sdk-3.0 and later.
Thanks,
Madhup
- (IBAction)showList:(id)sender{
//Switch to table view on segment control change
UISegmentedControl *segmentControl = (UISegmentedControl *)sender;
NSString *curSelection = [NSString stringWithFormat:#"%d", [segmentControl selectedSegmentIndex]];
//[segmentControl titleForSegmentAtIndex: [segmentControl selectedSegmentIndex]]];
NSLog(#"pressed button %#", curSelection);
if ([curSelection isEqualToString:#"1"]){
NSLog(#"TABLE SELECTED");
listController *listTable = [[listController alloc] init];
//Try this
listTable.places = self.places; // set the array contents here and check
[navController pushViewController:listTable animated:YES]; //SWITCH TO TABLE VIEW (listController)
} else {
tpbViewController *tpb = [[tpbViewController alloc] init];
NSLog(#"MAP SELECTED");
[navController pushViewController:tpb animated:YES];
}
}
Dont forget to write the accessors in ListController for places array. And let me know what happens.
When you go to display your tableview, call the reloadData method on it; if your datasource/delegate is assigned to the correct object then that will trigger the table view to ask the datasource/delegate for its cells, and it should display at that point.