iPhone - Array to UITableView - iphone

I can't display array in UITableView. The thing I do is - in viewWILLappear I'm creating array. In viewDIDappear I'm filling the array. But when I run [myArr count] or [myArr objectAtIndex:indexPath.row] in table setup I get empty table. If I define constant integer as row count and some constant string as cell text everything works fine. Is there some populate() method I have to run or is it a problem with some order of declarations?
Thanks for any help. Here's the code:
- (void)viewWillAppear:(BOOL)animated {
myArr = [[NSMutableArray alloc] initWithCapacity:100];
}
- (void)viewDidAppear:(BOOL)animated {
[self load_array];
}
- (void) load_array {
for (SomeObject *someObject in SomeObjects) {
[myArr addObject:someObject.someString];
NSLog(#"Value: %#", [myArr objectAtIndex:([myArr count]-1)]); // works
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [myArr count]; // works if I return const ("return 2")
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (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];
}
cell.textLabel.text = [myArr objectAtIndex:indexPath.row]; //=#"ASDF" works.
return cell;
}

You need to perform reloadData on your table view to make the view re-load the table cells.
Update: You should not allocate your array in the viewWillAppear, as this method might be called several times. Construct the array in the viewDidload: and fill it there, or in a background thread, or in the viewWillAppear: (using a conditional statement to check if its already filled). You should also make sure that you do not create a memory leak, from the code you provided it is likely that myArr will be replaced by a newly allocated array without being released.

Related

How can i use prototype cell in storyboard with search result controller

I have tableview with search result controller when search in search bar get this error indicate that there is no cell and get the below error .How can create my prototype cell in this method CellForRowAtIndexPath
Code :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"HoCell";
Ho *cell;
Ho *item;
if (tableView == self.searchDisplayController.searchResultsTableView) {
if (cell == nil)
{
cell = [[Ho alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"HoCell"];
}
item = [searchResultsController objectAtIndexPath:indexPath];
}
else{
cell = (Ho*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
item = [fetchedResultsController objectAtIndexPath:indexPath];
}
cell.ho.text = item.name;
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"se.png"]];
return cell;
}
Error :
*** Assertion failure in -[UISearchResultsTableView _configureCellForDisplay:forIndexPath:], /SourceCache/UIKit_Sim/UIKit-2372/UITableView.m:5471
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'
There may be two possibilities Here :
1) You are returning a number larger than your Array Count from
tableView:numberOfRowsInSection:. Don't.
2) One or more of your cell# outlets is not hooked up in your nib, or
is not hooked up to a UITableViewCell (or subclass). Hook them up
properly.
Go through this Ray Wenderlich's Link :
How to Add Search Into a Table View
Check this SO Questions :
1) UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath: Exception
2) ios 5 UISearchDisplayController crash
One More Beautiful Link : Custom Prototype Table Cells and Storyboards Just see this Portion :
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:UYLCountryCellIdentifier];
if (cell == nil)
{
[self.countryCellNib instantiateWithOwner:self options:nil];
cell = self.countryCell;
self.countryCell = nil;
}
// Code omitted to configure the cell...
return cell;
}
Your code seems to be buggy. You check for cell == nil while it is not set to nil initially. It also looks a bit strange that you allocate your cells in that way based on search mode.
Anyways, I would do it different way. Imho the way I do it is almost canonical :) Just use your search result to populate your cells with correct data for each case (search mode and normal mode). In this example, searchResult and dataSource are arrays with strings. I think in real life for you it will be something more complex like array of nsdictionary.
In your view controller:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)_section
{
/* Use correct data array so that in search mode we draw cells correctly. */
NSMutableArray *data = searching ? searchResult : dataSource;
return [data count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
/* Use correct data array so that in search mode we draw cells correctly. */
NSMutableArray *data = searching ? searchResult : dataSource;
static NSString *CellIdentifier = #"CellId";
CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomTableViewCell alloc] initWithIdentifier:CellIdentifier] autorelease];
}
/* Note this is only correct for the case that you have one section */
NSString *text = [data objectAtIndex:[indexPath row]]
cell.textLabel.text = text;
/* More setup for the cell. */
return text;
}
And here are delegate methods for search controller and some helpers:
- (void) searchTableView
{
NSString *searchText = searchBar.text;
for (NSString *item in dataSource) {
NSRange range = [item rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (range.length > 0) {
[searchResult addObject:item];
}
}
}
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
searching = NO;
}
- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
searching = NO;
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0]
withRowAnimation:UITableViewRowAnimationAutomatic];
[searchResult removeAllObjects];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchText
{
[searchResult removeAllObjects];
if ([searchText length] > 0) {
searching = YES;
[self searchTableView];
} else {
searching = NO;
}
return YES;
}
Hope this helps.
I have the same issue, here is what is did and it is now working perfectly..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Here is my code BEFORE
//
OPUsersTableViewCell *tableCell = [tableView dequeueReusableCellWithIdentifier:TableCellID];
// Here is my code AFTER
//
OPUsersTableViewCell *tableCell = [self.groupTableView dequeueReusableCellWithIdentifier:TableCellID];
Note:
self.groupTableView is where the prototype cell is...

iPhone: How to add rows in tableview after tabelview already loaded?

I have implemented "Add to Favourites" functionality for my iPhone application. It works fine except adding cells into my Favourite Table View during runtime. For example, I have given following methods.
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
tableView.hidden = YES;
warningLabel.hidden = YES;
// Load any change in favourites
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:kFavouriteItemsKey];
self.favourites = [NSKeyedUnarchiver unarchiveObjectWithData:data];
if([self.favourites count] > 0)
tableView.hidden = NO;
else
warningLabel.hidden = NO;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.favourites count]; // Favorites is a dictionary contains required data
}
- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [NSString stringWithFormat:#"index: %d",indexPath.row];
return cell;
}
This code works fine and display rows correctly for the first time only! After tableview is loaded and if I add new item(s) in favorites or delete any item(s), it doesn't make any difference to my tableview! I want to display exactly what is available in Favourites dictionary. It seems CellForRowAtIndexPath doesn't get invoked when ViewAppear again. Is there any method for TableView that I can use to achieve my requirements?
I think you've missed to call [tableView reloadData];
The very easy way is to just call [tableView reloadData] whenever you make any changes.
There is also a better (faster for large tables, and possibly animated; more elegant), but much more complicated way which I won't go into unless you decide the reloadData way isn't sufficient for you.

Problem with sectioning UITableViewController

I have a class that extends UITableviewController which displays a data type called "GigData" (which only contains strings for now). The content is stored in "data" which is an NSMutableArray containing NSMutableArrays containing "GigData". This array is passed to the instance of my class and the arrays inside arrays make up the sections of the table. Here is the code I have implemented so far:
#synthesize data = _data;
- (id)init
{
self = [super initWithStyle:UITableViewStyleGrouped];
_data = [[NSMutableArray alloc] init];
[[self navigationItem] setTitle:#"Gigs by Date"];
return self;
}
- (id)initWithStyle:(UITableViewStyle)style
{
return [self init];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return [_data count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [[_data objectAtIndex:section] 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];
}
NSMutableArray *sectionArray = [_data objectAtIndex:[indexPath section]];
GigData *gig =[sectionArray objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[gig description]];
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
GigData *temp = [[_data objectAtIndex:section] objectAtIndex:0];
return [temp date];
}
When I run the app, I can see everything sorted into the right groups and all the displays are correct, except for the final section, which keeps changing names, some of which have included "cs.lproj", "headers" and "method not allowed". Scrolling to the bottom of the table then towards the top crashes the app. Also, if I provide my own implementation for description for "GigData", the app crashes even worse, I cannot scroll to the second section at all. Data is declared as a property in the header file and is set to nonatomic and retain. I have also tried using the code inside the init method to create the data array inside this class, but this makes no difference. Some runnings of the app have said there is a problem in tableView:cellForRowAtIndexPath: when I create "sectionArray". Has any body got any suggestions as to what I am doing wrong?

UITableView crashes when datasource is connected in Interface Builder

- (NSInteger)numberOfSectionsInTableView:(UITableView *)cijferTableView{
return 1;
}
- (NSInteger)cijferTableView:(UITableView *)cijferTableView numberOfRowsInSection:(NSInteger)section {
return [marksArray count];
}
- (UITableViewCell *)cijferTableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [theTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [marksArray objectAtIndex:indexPath.row];
return cell;
}
I have a marksArray which is filled with strings.
The code worked fine until a quarter of an hour ago but since then it has been crashing when I load the view this code is in, without me changing anything.
When I, in interface builder, disconnect the datasource however, the view is loaded properly without a crash. But of course, it won't fill the table in that case.
What did I do wrong?
Update:
The error the console gives is terminate called after throwing an instance of 'NSException'
Also, i didnt exactly add anything into marksArray just yet. To test, i just have this:
//.h
NSMutableArray *marksArray;
and
//.m
marksArray = [NSMutableArray arrayWithObjects:#"1", #"2", nil;
It looks like you did a search and replace for "tableView" with cijferTableView and in doing so you renamed the methods, which will cause this to break. For example:
- (NSInteger)cijferTableView:(UITableView *)cijferTableView numberOfRowsInSection:(NSInteger)section {
return [marksArray count];
}
should be...
- (NSInteger)tableView:(UITableView *)cijferTableView numberOfRowsInSection:(NSInteger)section {
return [marksArray count];
}
1) You forgot to retain marksArray
2) Weird names for dataSource methods ('cijfer' stuff instead of tableView:numberOfRowsInSection: and tableView:cellForRowAtIndexPath:). They will not work.
Why are you renaming your delegate methods? Maybe those are causing some of your problems?

Cant bind data to a table view

I have retrieved data from Json URL and displayed it in a table view. I have also inlcuced a button in table view. On clicking the button the data must be transferred to a another table view. The problem is that i could send the data to a view and could display it on a label. But i couldnt bind the dat to table view ... Here's some of the code snippets...
Buy Button...
-(IBAction)Buybutton{
Product *selectedProduct = [[data products]objectAtIndex:0];
CartViewController *cartviewcontroller = [[[CartViewController alloc] initWithNibName:#"CartViewController" bundle:nil]autorelease];
cartviewcontroller.product= selectedProduct;
[self.view addSubview:cartviewcontroller.view];
}
CartView...
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
data = [GlobalData SharedData];
NSMutableArray *prod =[[NSMutableArray alloc]init];
prod = [data products];
for(NSDictionary *product in prod){
Cart *myprod = [[Cart alloc]init];
myprod.Description = [product Description];
myprod.ProductImage =[product ProductImage];
myprod.ProductName = [product ProductName];
myprod.SalePrice = [product SalePrice];
[data.carts addObject:myprod];
[myprod release];
}
Cart *cart = [[data carts]objectAtIndex:0];
NSString *productname=[cart ProductName];
self.label.text =productname;
NSLog(#"carts");
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [data.carts count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 75;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"cellforrow");
static NSString *CellIdentifier = #"Cell";
ProductCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell ==nil)
{
cell = [[[ProductCell alloc]initWithFrame:CGRectZero reuseIdentifier:CellIdentifier]autorelease];
}
NSUInteger row = [indexPath row];
Cart *cart = [[data carts]objectAtIndex:row];
cell.productNameLabel.text = [cart ProductName];
return cell;
}
I am also getting the following error in the console
2010-06-11 18:34:29.169 navigation[4109:207] *** -[CartViewController tableView:numberOfRowsInSection:]: message sent to deallocated instance 0xcb4d4f90
Your view controller is autoreleased that's why you have the error in the console.
CartViewController *cartviewcontroller =
[[[CartViewController alloc]
initWithNibName:#"CartViewController"
bundle:nil] ***autorelease***];
You should store your view controller in a member variable.
This is depreciated:
cell = [[[ProductCell alloc]initWithFrame:CGRectZero reuseIdentifier:CellIdentifier]autorelease];
Use initWithStyle:reuseIdentifier: instead.
Autorelease isn't a convenience function. It has a specific use. You're only supposed to use it when you are immediately handing an object off to an another external object. Don't use autorelease unless the sending object longer cares if the receiving object lives or dies.
A good rule of thumb is if you ever refer to the receiving object again in the sending object, don't autorelease the receiving object.