Table View not populating - iphone

I know this is an oft-asked question/problem. I've looked through a bunch of Q&A for my problem, but I guess I'm a little thick, because I didn't see an answer anywhere.
I have a file with in an array that I would like to use to populate a tableView.
The problem is that it's not being called. Neither is numberOfRowsInSection or numberOfSectionsInTableView. I far as I can see, only viewDidLoad was called.
I have 1 section, the number of elements in my array equals 3 (as opposed to nil).
Relevant code is here...
- (void)viewDidLoad {
[super viewDidLoad];
FileControl *fileArray = [[FileControl alloc] init];
matArray = [fileArray findUniqueItemsInArray:0 :[fileArray setFileToArray]];
[fileArray release];
NSLog(#"%i \n %#", [matArray count], matArray); // matArray is filled.
NSLog(#"ViewDidLoad"); }
- (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];
}
NSLog(#"CellForRowAtIndexPath");
NSString *text = [matArray objectAtIndex:[indexPath row]];
[[cell textLabel] setText:text];
return cell; }
#interface MaterialTableViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource> {
IBOutlet UITableView *materialTableView;
NSArray *matArray;
}
#property (nonatomic, retain) NSArray *matArray;
#end
The other methods are standard.
I guess my problem lies in that I don't completely understand the flow well enough.
Any help would be greatly appreciated. Thanks in advance.

Have you set your UIViewController subclass to be the delegate and dataSource of the UITableView in question? Without doing so, none of the methods you mention will be called.

I suppose you are using a UITableViewController.
If you are using UITableView it is a little bit more complicated (in this case you need to implement UITableViewDelegate, UITableViewDataSource protocols).
[update] This is not your case, you are using UITableViewController.
Add this line to the end of your viewDidLoad method:
[self.tableView reloadData];
Or move this:
FileControl *fileArray = [[FileControl alloc] init];
matArray = [fileArray findUniqueItemsInArray:0 :[fileArray setFileToArray]];
[fileArray release];
to the init method. Your init method should look like this:
- (id)initWithStyle:(UITableViewStyle)style {
if ((self = [super initWithStyle:style])) {
FileControl *fileArray = [[FileControl alloc] init];
matArray = [fileArray findUniqueItemsInArray:0 :[fileArray setFileToArray]];
[fileArray release];
NSLog(#"%i \n %#", [matArray count], matArray); // matArray is filled.
NSLog(#"ViewDidLoad");
}
return self;
}
If you do not see any message in the log, it means that you are not using that method to initialize your object.
Please show all your code in the .m and .h files.

I have a suggestion. Just give a shot for a test. In the - (void)viewDidLoad declare this.
instead of : matArray = [fileArray findUniqueItemsInArray:0 :[fileArray setFileToArray]];
Use this: matArray = [[NSArray alloc] initWithArray:[fileArray findUniqueItemsInArray:0 :[fileArray setFileToArray]]];

Did you use
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.matArray count];
}

make sure you have added your tableview delegate to your .h file as shown below.
#interface YourViewController : UIViewController <UITableViewDelegate> {
}
Also make sure that you have connected your datasource and delegate in interface builder.
Do this by doing:
double click on your .xib file so it opens in interface builder.
left click on your tableview just once so its highlighted blue
right click on your tableview now and a menu should pop up.
drag the datasource & delegate to the files owner box.
make sure to save changes while in interface builder.
This should "connect" all the pieces needed to get it to work.
Happy Coding!!

Related

iPhone:TableView cellForRowAtIndexPath method issue

I am facing a crashing problem in cellForRowAtIndexPath tableview delegate method
#interface EventListView : UIViewController <UITableViewDelegate, UITableViewDataSource>
IBOutlet UITableView *tblView;
NSMutableArray *arr_EventValues,*arr_Event_Details;
NSMutableArray *arr_EventListDetails;
#property(nonatomic, retain)NSMutableArray *arr_EventValues,*arr_EventListDetails, *arr_Event_Details;
#property(nonatomic, retain)UITableView *tblView;
- (void)viewDidLoad
{
appdelegate = (VibesGuideAppDelegate *)[[UIApplication sharedApplication] delegate];
ViewCalendar = [[CalendarView alloc] initWithNibName:#"CalendarView" bundle:[NSBundle mainBundle]];
[self.navigationController.navigationBar setHidden:YES];
self.arr_Event_Details = [[NSMutableArray alloc] init];
self.arr_EventValues = [[NSMutableArray alloc] init];
[super viewDidLoad];
}
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([self.arr_EventListDetails count] > 0)
{
return [self.arr_EventListDetails count];
}
return 0;
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
// ------------------------------- Custom cell ------------------------------
Customcell *cell = (Customcell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[[Customcell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.text = #"Hello";
return cell;
}
* -[EventListView tableView:cellForRowAtIndexPath:]: message sent to deallocated instance 0x60e01b0 and I used tableview from xib and set all connections and also got arrayvalues in numberOfRowsInSection in method but in cellForRowAtIndexPath method is not called so please give me idea my issue....
Thanks in advance.
At first it seems your some variable gets released. Make sure you have properly allocated it. If you have declared #property for it you better use the variable as self.variable. You can use retain and in case of IOS 5 strong in property declaration.
Just to be sure you can track if any variable gets released via setting NSZombieEnabled to YES. With zombies enabled, messages to deallocated objects will no longer behave strangely or crash in difficult-to-understand ways, but will instead log a message and die in a predictable and debugger-breakpointable way. You can set NSZombieEnabled by the following steps.
Select Product from the menu bar above. Keep alt/option pressed and select "Test..." or "Run...". Go to the Arguments tab, and add NSZombieEnabled YES in the "Environment Variables" section.
Your tableview itself is already released - the error message says that you send the cellForRowAtIndexPath message to a deallocated instance of the table view - so your problem lies somewhere in not retaining or releasing the EventListView and cannot be seen in the code displayed here.
Check this one:
Table DataSource and delegate is set or not.
Used array in cellForRowAtIndexPath is properly set with property and synthesized as well used with self. name.
First of all you dequeue the cell and then create a new one. This is not a good practice, if you are able to dequeue a cell you should not create a new one. You should have something like this:
Customcell *cell = (Customcell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[[Customcell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
fix this and let me know if you are still running on the same problem.

NSArray released early

I'm having a problem with my iPhone app crashing when I scroll down on a UITableView. I set NSZombieEnabled to YES, and found out that the NSArray I'm using to fill the table is getting dealloced somehow.
#import "RootViewController.h"
#implementation RootViewController
#synthesize flashsets;
- (void)viewDidLoad
{
//Unrelated code removed from this post
NSString *listofsetsstring = [[NSString alloc]
initWithContentsOfFile:pathtosetsdata
encoding:NSUnicodeStringEncoding
error:&error];
flashsets = [listofsetsstring componentsSeparatedByString:#"\n"];
[super viewDidLoad];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [flashsets count];
}
// Customize the appearance of table view cells.
- (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];
}
// Configure the cell.
NSLog(#"IndexPath.row = %i", indexPath.row);
cell.textLabel.text = [flashsets objectAtIndex:indexPath.row]; <<<< CRASH HERE!!
return cell;
}
#end
I'm getting message sent to deallocated instance 0x4ebae20 at the bolded line. In my .h I used #property (nonatomic, retain) NSArray *flashsets;, I thought the retain part should keep it from deallocating.
How do I keep it from doing this?
Problem is with :
flashsets = [listofsetsstring componentsSeparatedByString:#"\n"];
change it to
flashsets = [[listofsetsstring componentsSeparatedByString:#"\n"] retain];
edit: the retain in property is only used if you use the setter, so it will only work if you use the following line:
[self setFlashsets:[listofsetsstring componentsSeparatedByString:#"\n"]];
in you viewDidLoad it should be self.flashsets = this will insure the accessor method is used to set the value, and thus the 'retain' behaviour you specified on the property definition will be implemented.
flashsets = [listofsetsstring componentsSeparatedByString:#"\n"];//it returns autorealesed NsArray.So If you want Longer Use.you should get Owner ship from that array By Alloc or Copy Or Retain.
flashsets = [[listofsetsstring componentsSeparatedByString:#"\n"] retain];
or
flashsets = [[listofsetsstring componentsSeparatedByString:#"\n"]copy];
or
flashsets = [[NsArry alloc ] initWithArray:[listofsetsstring componentsSeparatedByString:#"\n"]];
I don't know if this will help, but you may want to use the setter and getter methods when referring to flashsets - the retain part of the property doesn't apply (I don't think) when setting the variable directly.

UITableView with JSON help

I am trying to feed in some JSON data to my iPhone app, the data is coming in fine as I have NSLog's telling me so.
The problem I am having is trying to get the results to show in a UITableView. I have a navigation controller underneath a tab bar controller, the navigation controller contains a table view controller which loads another NIB file with a table view connected to a class which is the delegate and data source delegate.
I also need to categorize the results into sections - these being
England
Scotland
Wales
N.Ireland
To get an idea of what JSON string I am using see this one.
As you can see the JSON does not cater for the sections but I am yet to implement this, so i would need to know beforehand so I do not have to amend much code later on.
OK - I am using Stig JSON parser.
Here is my ListVenuesView.h (connected to table view)
#import <UIKit/UIKit.h>
#import "SBJson.h"
#interface ListVenuesView : UITableViewController <UITableViewDelegate, UITableViewDataSource> {
IBOutlet UITableView *venueList;
NSMutableDictionary *jsonArray;
}
#property (nonatomic, retain) IBOutlet UITableView *venueList;
#property (nonatomic, retain) NSMutableDictionary *jsonArray;
#end
jsonArray is used to store the JSON data and eventually the proper array.
And here is my ListVenuesView.m (key areas in question)
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"Table View Loaded");
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
// This is where we load the JSON data
NSURL *jsonURL = [NSURL URLWithString:#"http://www.thebigfishexperience.org.uk/sources/ajax/venue-json.php?location=peterborough"];
NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];
NSLog(#"%#", jsonData);
// Convert jsonData to array
self.jsonArray = [jsonData JSONValue];
NSLog(#"%#", jsonArray);
NSLog(#"count is: %i", [self.jsonArray count]);
// Release NSString and NSURL
[jsonURL release];
[jsonData release];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.jsonArray count];
}
- (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];
}
NSMutableDictionary *dict = [self.jsonArray objectAtIndex: indexPath.row];
cell.textLabel.font = [UIFont fontWithName:#"Arial" size:15.0];
cell.textLabel.text = [dict objectForKey:#"venueName"];
cell.detailTextLabel.text = [dict objectForKey:#"venueCordDist"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// Configure the cell...
return cell;
Also how can I use the data in the cells to go to another subview of the nav controller which gives me a back button and displays the info from the JSON string just for that particular cell that has been tapped.
I think this has something to do with it? Not sure though as this is my first app i am building! So probably expect more pleas of assistance - ha ! ;)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:#"Nib name" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
*/
}
On selecting a row, as mentioned by u, we are navigating to another view. Let us assume that the view controller is DetailViewController which is a sub-class of UIViewController.
In the DetailViewController.h , declare a NSDictionary object.
In DetailViewController.m, add
-(void)setVenueDict:(NSDictionary*)venueDict
{
if( _venueDict )
{
[_venueDict release];
}
_venueDict = [venueDict retain];
}
In ParentViewController, ur didSelectRow.. method should be like this.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:#"Nib name" bundle:nil];
// ...
// Pass the selected object to the new view controller.
NSDictionary *dict = [self.jsonArray objectAtIndex: indexPath.row];
[detailViewController setVenueDict:dict];
detailViewController.title = [dict objectForKey:#"venueName"];
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
}
In the second view controller, u can do whatever u want with the _venueDict.
Nathan,
since you want to reuse the data parsed from the JSON feed over more than one ViewController the best way to approach this is to build an object Model so that you can pass the object for the selected row in the list to the detail ViewController.
I would also separate the JSON parsing code into a separate class and not keep it in the ViewController.
You can find classes to fetch JSON on this link.
The result from the custom code to parse the JSON feed would give back a NSDictionary with as keys the section names you mention. And the value in the NSDictionary for those keys would be an array of your custom objects that contain all the relevant data for one row (and detail screen).
Hope this helps you on your way.
jsonArray is NSMutableDictionary.
have to use
[jsonArray objectForKey:key];
//check this line
NSMutableDictionary *dict = [self.jsonArray objectAtIndex: indexPath.row];
this may help.

iOS: Custom UITableViewCell touch receiver confusion

have seen similar questions but couldn't find a definitive answer.
Having mastered regular tables of most types, I am doing some conceptual experiments with custom table cells to get familiar with how this works. I want to have a custom subclass of UITableViewCell which loads a nib to the contentView. I may want to implement different editing styles at some later point but want to reuse the custom view in different parts of my application, however, i'm having problem receiving the didSelectRowAtIndexPath message in my calling UITableViewController.
Here's the hierarchy which is built from a basic view template.
CustomCellViewController: A stock XCode objective-c class sublcassed from UITableViewCell
#interface CustomCellViewController : UITableViewCell {
IBOutlet UILabel *lbl;
}
#property (nonatomic, retain) IBOutlet UILabel *lbl;
#end
#implementation CustomCellViewController
#synthesize lbl;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
NSArray *a = [[NSBundle mainBundle] loadNibNamed:#"customCellView" owner:self options:nil];
UITableViewCell *tc = [a objectAtIndex:0];
NSLog(#"Cell loaded from nib");
[self.contentView addSubview:tc];
}
return self;
}
.. the other stock methods are unchanged ..
#end
I realise that the init method could be simplified but this is my first attempt.
The XIB file's owner is my custom class (CustomCellViewController), has a UITableViewCell and a label (linked to the outlet 'lbl' on it) positioned half way accross, leaving plenty of the underlying UITableViewCell clickable.
RootViewController is a standard, stock XCode subclass of UITableViewController
RootViewController sets up an instance variable "CustomTableCellController *myCustomCell"
The cellForRowAtIndexPath: is as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"myCustomCell";
CustomCellViewController *cell = (CustomCellViewController *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomCellViewController alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
NSLog(#"Creating New cell for position %d", indexPath.row);
} else {
NSLog(#"Reusing cell for position %d", indexPath.row);
}
// Configure the cell.
cell.lbl.text = [NSString stringWithFormat: #"Hi There %d", indexPath.row];
return cell;
}
And in the same RootViewController.m, my didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Cell tapped at row %d", indexPath.row);
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
*/
}
Designed at present, to purely output a log message when tapped.
numberOfSectionsInTableView returns 1
numberOfRowsInSection returns 50
This all compiles and runs fine, iPhone simulator starts, I see a table on the display, my output log confirms it has created 9 versions of CustomCellViewController and I can see the reuse stack via the NSLog() comments.
I just can't select a row, doesn't matter where I click in the custom cell, nothing gets to my didSelectRowAtIndexPath: in my RootViewController which is where I expect it.
Is it that I have I not set a delegate somewhere and if so, how? Do I need to do this via a first responder? (ie, create a method in my CustomCellViewController class, link the UITableViewCell from the XIB to that method and then call [super didSelectRowAtIndexPath] - but how do I pass the indexPath?
Am I not responding to a message from my XIB in it's owner and then passing it on (is this how I do it?)
I read through all the apple docs to get to this stage but couldn't quite decipher how touch messaging happened.
Slightly confused!
May be you have forget to set data source and delegate if the tableview object set it as like below
tbl.delegate = self;
tbl.dataSource = self;

cellForRowAtIndexPath never called

I've subclassed UITableView to create my own data retrieval system, as described in Apple's own Core Data tutorial, but I've hit a problem. The substitute cellForRowAtIndexPath method in my custom table never gets called, not even when I call reloadData or setNeedsDisplay. I've been hunting around for solutions to this one, and it seems that this error can be caused by a multitude of problems. However I've checked all the ones I can find and cannot see anything missing. Can anyone tell me what's likely to be wrong?
P.S. I know the UITableViewDataSource protocol needs to be in triangular brackets, but I couldn't find out how to show triangular brackets on the page without deleting the text between them.
H-File
#interface DataTable : UITableView <UITableViewDataSource> {
NSMutableArray *list;
}
#property (nonatomic, retain) NSMutableArray *list;
#end
M-File
#implementation DataTable
#synthesize list;
-(id) initWithFrame:(CGRect)rect Style:(UITableViewStyle)style{
if (self = [super initWithFrame:rect style:style]){
list = [[NSMutableArray alloc] init];
self.dataSource = self;
}
return self;
}
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [list count];
}
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellID = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil){
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:cellID] autorelease];
}
CH *this = (CH *)[list objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [this.clusterName mutableCopy];
return cell;
}
-(void) dealloc{
[list release];
[super dealloc];
}
#end
Never mind, think I've found it. Basically, you can't set the datasource delegate in that part of the program. Need to do it from its owning view controller.