Properties in custom UITableViewCell are not getting initialized for a UISearchDisplayController's table - objective-c

I am using a UISearchDisplayController to be able to display a table with custom cells based on some data I am retrieving from a server.
First I set the UISearchDisplayController inside my UIViewController.
self.searchController = [[UISearchDisplayController alloc]
initWithSearchBar:self.mySearchBar contentsController:self];
self.searchController.delegate = self;
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
My UIViewController also implements the UISearchBarDelegate, so I can determine when a search starts. I set up a block so when my api call returns it gets called and a dictionary of results is saved in the self.searchResults property:
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
// here we make the api call
[api getSomeInfo:searchBar.text complete:^(NSDictionary *json) {
self.searchResults = json;
[self.searchController.searchResultsTableView reloadData];
}];
}
Now, the problem I have is that in my UITableViewDataSource method, where I return the custom cell. My cell is instantiated, but it's IBOutlets never get initialized, so I cannot set their content (text, images, etc) properly:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == self.searchController.searchResultsTableView) {
cell = [tableView dequeueReusableCellWithIdentifier:#"SearchResultsCellIndentifier"];
if (cell == nil) {
cell = [[SearchResultsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.customLabel.text = [self.searchResults objectForKey:#"customText"]; // cell exists but cell.customLabel is nil!!
}
}
Why is the content nil? Is there somewhere in my Custom Cell class where I should be setting the content up?
Thanks!

I think your problem is that you used the variable cellIdentifier when creating the cell, but a string constant when dequeuing.
Simply always recreating a cell will work, but is not efficient at all and leads to major memory leaks.
You should first set the cellIdentifier according to which table view you are in, and which kind of cell you need, then dequeue with that cellIdentifier, and then create a new one if needed.

Related

UITableView Data Inconsistency

I have a UITableView backed by a NSArray.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.data.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}
id item = [self.data objectAtIndex:indexPath.row];
cell.item = item;
return cell;
}
Very standard. Now the problem is that reloadData will ask for numberOfSections and numberOfRows synchronously, but will call cellForRow asynchronously. So sometimes, by the time cellForRowAtIndexPath gets called, the data array has changed, and so [self.data objectAtIndex:indexPath.row] gets an out of bounds exception and crashes the app. How do I avoid this?
Note that every time I set the data array, I also call [self.tableView reloadData].
cellForRowAtIndexPath gets called frequently, (on scroll etc), you could just add a simple line of code to check if the size of the data array is smaller than the cell being requested. Although this means you might end up with blank cells.
I'd set breakpoints on both methods, right click the breakpoints -> "edit breakpoint" and tick "automatically continue after evaluating". Then click "add action" -> "debugger command" and then type "po data" or "po [data count]".
This will print information about the array in the debug console every time the breakpoint is hit (without stopping). You should then be able to look through the debug output and see where it is falling out of sync. Add some NSLog statements to to tell you which method is is being called etc and work from there.
I think the best way to avoid such a situation is to avoid user interaction while data is updated.May be you can show a screen to user that "updating.." and an activity indicator.
Another way is that to have another array to populate new data, handling can be done in separate thread and at times only it is assigned back to the datasource array with reloading call after that.There also a screen with same can be used while datasource array gets changed
Quick hack I used, try this and see if it works for you:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}
// -----------------------------------------------------------------
// the magical line that prevents the table from fetching the data
// -----------------------------------------------------------------
if([indexPath row] < [self.data count])
{
id item = [self.data objectAtIndex:indexPath.row];
cell.item = item;
}
return cell;
}
:D
You should store a local array, that doesnt get modified. then, when your base array changes, you can update your storred array safely. Look into adding/removing cells from a table view using the built in api Add rows to existing UITableView section

Setting static cells in uitableview programmatically

I am programmatically creating a tableview in objective c. How can I make the cells static programmatically?
Thanks
Making cells static programmatically doesn't really make sense. Static cells are basically only for Interface Builder and requires the entire TableView to be static. They allow you to drag UILables, UITextFields, UIImageViews, etc. right into cells and have it show up just how it looks in Xcode when the app is run.
However, your cells can be "static" programmatically by not using an outside data source and hardcoding everything, which is usually going to be kind of messy and generally a poor idea.
I suggest making a new UITableViewController with a .xib and customizing it from there if you want "static" cells. Otherwise, just hardcode all your values and it's basically the same thing, but is probably poor design if it can be avoided.
By using a distinct cell identifier for each one you will get it. You could use something like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = [NSString stringWithFormat:#"s%i-r%i", indexPath.section, indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
//you can customize your cell here because it will be used just for one row.
}
return cell;
}
You could also do it the old fashioned and just create the cell the way you want depending on the NSIndexPath, this works with Static Cell TVC's and regular table views (don't forget to return the proper number of sections and rows in their datasource methods):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
switch indexPath.row {
case 0:
// First cell, setup the way you want
case 1:
// Second cell, setup the way you want
}
// return the customized cell
return cell;
}
I you want to create cells structure for example for a settings screen or something like that and you maybe need just to modify some cells content but not their number or sections structure you can overload method of your UITableViewController subclass like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *aCell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
// Configure the cell...
if ([aCell.reuseIdentifier isEqualToString:#"someIdentifier"]){
//some configuration block
}
else if ([aCell.reuseIdentifier isEqualToString:#"someOtherIdentifier"]) {
//other configuration block
}
return aCell;
}
But you can make it in a better way with a little bit more code;
1) In the begining of your .m file add typedef:
typedef void(^IDPCellConfigurationBlock)(UITableViewCell *aCell);
2) add cellConfigurations property to your TablviewControllerSubclass extention:
#interface IPDSettingsTableViewController ()
#property (nonatomic, strong) NSDictionary *cellConfigurations;
#property (nonatomic) id dataModel;
#end
3) Modify your static cells of TableviewController subclass in storyboard or xib
and add unique cellReuseIdentifier for each cell you want to modify programmatically
4) In your viewDidLoad method setup cellsConfiguration blocks:
- (void)viewDidLoad
{
[super viewDidLoad];
[self SetupCellsConfigurationBlocks];
}
- (void)SetupCellsConfigurationBlocks
{
//Store configurations code for each cell reuse identifier
NSMutableDictionary *cellsConfigurationBlocks = [NSMutableDictionary new];
//store cells configurations for a different cells identifiers
cellsConfigurationBlocks[#"someCellIdentifier"] = ^(UITableViewCell *aCell){
aCell.backgroundColor = [UIColor orangeColor];
};
cellsConfigurationBlocks[#"otherCellIdentifier"] = ^(UITableViewCell *aCell){
aCell.imageView.image = [UIImage imageNamed:#"some image name"];
};
//use waek reference to self to avoid memory leaks
__weak typeof (self) weakSelf = self;
cellsConfigurationBlocks[#"nextCellIdentifier"] = ^(UITableViewCell *aCell){
//You can even use your data model to configure cell
aCell.textLabel.textColor = [[weakSelf.dataModel someProperty] isEqual:#YES] ? [UIColor purpleColor] : [UIColor yellowColor];
aCell.textLabel.text = [weakSelf.dataModel someOtherProperty];
};
weakSelf.cellConfigurations = [cellsConfigurationBlocks copy];
}
5) overload tableView:cellForRowAtIndexPath method like this:
#pragma mark - Table view data source
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *aCell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
// configure cell
[self configureCell:aCell withConfigurationBlock:self.cellConfigurations[aCell.reuseIdentifier]];
return aCell;
}
- (void)configureCell:(UITableViewCell *)aCell withConfigurationBlock:(IDPCellConfigurationBlock)configureCellBlock
{
if (configureCellBlock){
configureCellBlock(aCell);
}
}
It is pretty common to want to build a simple table to use as a menu or form, but using the built in API with the datasource and delegate callbacks don't make it easy to write or maintain. You may need to dynamically add/remove/update some cells, so using Storyboards by itself won't work.
I put together MEDeclarativeTable to programmatically build small tables. It provides the datasource and delegate for UITableView. We end up with an API where we provide instances of sections and rows instead of implementing datasource and delegate methods.

Confusion with storyboard and UITableView data source: How to display text in a cell

So I've been given an assignment in my Mobile apps class: make a color game app for the iphone.(The description of how to game works is at the top of the pasted viewcontroller.h file below.)
I'm very new to Objective-C and cocoa, but have managed to troubleshoot and fix a lot of things in this app. The problem I have right now is that I don't know how to properly initialize and send UITableViewCells to the view. I'm confused because all of the tutorials I've found online use datasource methods to change different attributes of the UITableView and the cells as well. I'm not sure how these methods will interact with the controls I've already placed. I'm confused because I added them by the storyboard file, not by defining tableview attributes with datasource code.
My immediate issue is that my program won't display the proper text to the cells textlabel and detailtextlabel.
I've looked everywhere online for UITableView and UITableViewCell tutorials, but they are all from years ago and I'm not sure if the advent of the storyboard has changed the way I would treat these controls.
All of the code I've written is either in the viewcontroller.m or viewcontroller.h files.
The method within ViewController.m file, that should call the cell and display text and detail text:
-(IBAction)enterClicked
{
//On enter- send instance colors to the colorTable row[i], perform comparisons and append the resulting symbols to the instanceResults String. Send instanceResults string to the resultTable row[i]. When game counter reaches 6, gameOver. If on comparisons check, the instanceColors are the same as the gameColors, then the player wins.
[self checkForLoss];
if(!self.gameOver)
{
resultOfGuess = [self comparePlayerInputToGameColors:guessColors];
[listOfGuesses addObject:guessColors];
[listOfOutcomes addObject:resultOfGuess];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_numberOfTurnsPlayed inSection:0];
UITableViewCell *thisCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
thisCell.textLabel.text = [self.listOfGuesses lastObject];
thisCell.detailTextLabel.text = [self.listOfOutcomes lastObject];
[guessColors setString:#""];
if([self checkForWin:resultOfGuess])
[UpdateLabel setText:#"You have won!"];
else
[UpdateLabel setText:#""];
self.colorCounter = 0;
self.isStepOne = YES;
_numberOfTurnsPlayed++;
}
else
{
if([self checkForLoss])
[UpdateLabel setText:#"You have lost!"];
}
}
The UITableView DataSource Methods I've called at the bottom of the viewcontroller.m file:
#pragma mark - UITableViewDataSource protocol
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if(section == 0)
return #"Guesses: Results:";
return 0;
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 6;
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
}
return cell;
}
So my questions are: Can I change a control's properties with datasource methods, if I created the controls through the storyboard? How do I properly display the text in a uitableview's cells?
Edit/update: Thank you, I've used your advice jrturton, but now I've found something peculiar that may be the source of my problems. in my viewController.h file I've changed my header from
ViewController: UIViewController to ViewController: UITableViewController
Thinking that the datasource methods I call within the viewcontroller files have to be able to call the same methods and properties of the class that I call in the header-- Also, I see this done in other UITableView tutorial files.
The problem is that when I change the header to read-- ViewController: UITableViewController -- and I try to compile, I get this error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UITableViewController loadView] loaded the "2-view-3" nib but didn't get a UITableView.'
It compiles fine if I use just :UIViewController in the header file though.
Any ideas?
Further update: I''ve noticed within my storyboard that the only available ViewController object is a UIViewController object, while in the other tutorial files I've seen, this ViewController object is a UITableViewController object. I imagine this is my problem, but I can't seem to switch my UIViewController object to a UITableViewController. All I can do is create a new one, which isn't what I want, I imagine.
Your action method should update the data model (which I think it does, since it changes your listOfGuesses array). You then need to let your table view know that you have added or updated rows so that it can re-load them for you - check the UITableView documentation for reloading data or specific rows.
Creating a cell outside of the datasource methods isn't going to let that cell appear in your table.
At the moment I'm guessing you have 6 empty cells in your table view? You need to populate the text and detail labels in your cellForRowAtIndexPath method. The difference now there are storyboards is that you don't need to do the if (cell == nil) bit, as long as you have set the re-use identifier in your storyboard prototype cell then it will do all that for you. So your cellForRowAtIndexPath method can be reduced to:
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
// This will dequeue or create a new cell based on the prototype in your storyboard
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
// Put your actual configuration here based on your model array
cell.textLabel.text = #"Hello";
return cell;
}
Further hints (this is homework so I'm not giving full samples)
'indexPath.row` in the above method will give you the index from your model array that the cell refers to
You have defined the table as having 6 rows, but you are adding items to your model arrays as you go - so when the table asks for row 5, and your model only has 3 entries, you need to deal with this. Consider changing the number of rows in the table dynamically and using table view methods to indicate that new rows have been added. Again, see the UITableView documentation for this.
Typically the text is set in each cell by accessing the setText property:
[[cell textLabel] setText:#"static string"];
or
[[cell textLabel] setText:someNSString];
or with .dot notation
cell.textLabel.text = someNSString;
return cell;
BTW this is done in the method:
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:

Crashing App when scrolling UItableView and hitting back

I am using a navigation controller to get to the UITableView. In this UItableView, there is a search bar and 50 cells. When i don't scroll and then hit back, the application acts normally but when i scroll down like 10 cells and then hit back, my application crashes with EXC_BAD_ACCESS Error. Any idea wat may be the reason of this crash?
In dealloc, I am releasing all the objects I created in the header file:
- (void)dealloc
{
[listContent release];
[filteredListContent release];
[tmpCell release];
[cellNib release];
[super dealloc];
}
and for the function creating the cells, it is as follows: ( Note I am doing an alternate UItableView with a searchBar)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *kCellID = #"cellID";
ApplicationCell *cell = (ApplicationCell *)[tableView dequeueReusableCellWithIdentifier:kCellID];
if (cell == nil)
{
[self.cellNib instantiateWithOwner:self options:nil];
cell = tmpCell;
self.tmpCell = nil;
}
/*
If the requesting table view is the search display controller's table view, configure the cell using the filtered content, otherwise use the main list.
*/
NSDictionary *dataItem;
if (tableView == self.searchDisplayController.searchResultsTableView)
{
dataItem = [self.filteredListContent objectAtIndex:indexPath.row];
}
else
{
dataItem = [self.listContent objectAtIndex:indexPath.row];
}
// Display dark and light background in alternate rows -- see tableView:willDisplayCell:forRowAtIndexPath:.
cell.useDarkBackground = (indexPath.row % 2 == 0);
// Configure the data for the cell.
cell.icon = [UIImage imageNamed:#"iTaxi.jpeg"];
cell.publisher = [dataItem objectForKey:#"Number"];
cell.name = [dataItem objectForKey:#"Name"];
cell.price = [UIImage imageNamed:#"order-taxi.png"];
return cell;
}
ViewDidUnload has the same code as dealloc
That error occurs because somewhere in your code you're setting scrollEnabled to "NO" (probably when you activate the searchbar):
self.tableView.scrollEnabled = NO;
I mean, if your searchText length is equals to 0 (you just entered on the search mode), you cannot disable the tableview scroll.
Hope this helped you.
Good luck, good coding!
Fábio Demarchi
When you press back while the tableview is being scrolled, the app will get crashed since the deallocated tableview instance's datasource(rarely delegate) protocol's method being called. So we could get the crash since we're accessing deallocated instance.
To avoid this just add the dealloc method in the particular view controller class, and set the corresponding protocol's to nil.
-(void)dealloc {
self.yourTableView.delegate = nil;
self.yourTableView.dataSource = nil;
}
Happy Coding :)
This is because the cells are recreated for visible rows. That is, cellForRowAtIndexPath is called for visible rows when you scroll the tableView. Remove that condition if(cell==nil) in cellForRowAtIndexPath.

UITableView "cellForRowAtIndexPath" method gets called twice on a swipe abruptly

I think many of us has faced this problem on UITableView delegate method - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath which gets called twice.
In my application I transforming the tableView. The code is:
CGAffineTransform transform = CGAffineTransformMakeRotation(-M_PI/2);
theTableView.transform = transform;
theTableView.rowHeight = self.bounds.size.width;
theTableView.frame = self.bounds;
Now inside the delegate method I am doing a couple of things:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
modelRef.currentCellAtIndexPathRow = indexPath.row;
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier frame:self.bounds] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
modelRef.currentPageIndex = (indexPath.row + 1);
[cell showPage];
NSLog(#" visible cell %i ",[[tableView visibleCells] count]);
return cell;
}
At a time 1 cell is visible, but first time when the application launches. The log shows visible cells 0.
Many a times this particular delegate method gets called twice abruptly.
How can I solve this?
I think an immediate fix is just to set a flag which changes the first time it is hit, so then you ignore the second call. It's probably not the perfect solution, and I can't tell you why it gets hit twice - but this will work. (I have experienced exactly the same behavior when I implemented an Apple delegate from the UIWebView class)
EDIT:
Create a BOOL member in the class header, then in the init set the value to be YES. So if the BOOL is called mbIsFirstCall for example, in your delegate method, do the following:
if (mbIsFirstCall)
{
// do your processing, then the line below
mbIsFirstCall = NO;
}
else
{
// you don't need this else, but just for clarity it is here.
// you should only end up inside here when this method is hit the second time, so we ignore it.
}