How can I check if a reuse identifier has been registered with a UITableView already? - objective-c

In iOS apps, we have to register nib files with our table view before we can use UITableView#dequeueReusableCellWithIdentifier.
Example:
static NSString *myReuseIdentifier = #"MyReuseIdentifier";
UINib *cellNib = [UINib nibWithNibName:myReuseIdentifier bundle:nil];
[self.tableView registerNib:cellNib forCellReuseIdentifier:myReuseIdentifier];
Is there a way to check if a Nib has already been registered with a UITableView?
I have a custom cell that I use in various tables across several controllers in my app. I'd like to move some of the code to a macro. Something like
-(CustomCell *)customCell:(UITableView *)tableView
{
static NSString *reuseIdentifier = #"MyReuseIdentifier";
if (![table hasAlreadyRegisteredNib:reuseIdentifier]){
UINib *cellNib = [UINib nibWithNibName:reuseIdentifier bundle:nil];
[self.tableView registerNib:cellNib forCellReuseIdentifier:reuseIdentifier];
}
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
return cell;
}

I am not sure if it that what you intend, but
-dequeueReusableCellWithIdentifier:
returns nil if the cell is not ready to reuse. Otherwise, it returns the cell, so you can simply try.

I believe the point of registerNib:forCellReuseIdentifier: is to reduce boilerplate code. Could you simply call this once in your viewDidLoad method?

Related

Unrecognized selector sent to instance when creating cell

I'm trying to reuse cell created in my storyboard,
I'm using this code:
MyTableView * mytableview;
UIStoryboard *sb = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
mytableview = [sb instantiateViewControllerWithIdentifier:#"myTable"];
AlertCell *cell;
cell = [mytableview.tableView dequeueReusableCellWithIdentifier:#"alertCell"];
cell.message.text = #"some text";
return cell;
I get this error:
[__NSArrayM objectForKeyedSubscript:]: unrecognized selector sent to instance 0xe02b7d0
this line eventually generates the error:
[mytableview.tableView dequeueReusableCellWithIdentifier:#"alertCell"];
The table view when using the cell is programaticlly created.
Everything i wanted works! but i got the errors in the log anyway
Thanks a lot!
You cannot create the table view when the cell is created.
You have to create the table view in a method that i called when the view controller is created, such as viewDidLoad.
Then in the cell method use the tableView pointer that is included in the method.
Also, the error actually indicates a problem with your datasource as well.
There are so many apparent knowledge gaps, maybe the best way is to read through the Table View Programming Guide.
I didn't exactly understand when you are creating table. You should not instantiate at the same time. Why you needed to call this line?
mytableview = [sb instantiateViewControllerWithIdentifier:#"myTable"];
If you want to use tableview, just create it normally and add it to your viewcontroller instead of using above line of code in viewDidLoad.
UITableView *tableView = [[UITableView alloc]initWithFrame:tableFrame style:UITableViewStylePlain];
tableView.rowHeight = 45;
[self.view addSubview:tableView];
tableView.delegate = self;
tableView.datasource = self;
Implement tableview's data source and delegate methods. And in cellForRowAtIndexPath::
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"newFriendCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"newFriendCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
//do your stuff
return cell;
}

How to implement didSelectRowAtIndexPath method with sectioned UITableView

I have been implementing a app with sectioned UITableView. In the tableview, I used a array, called sections, to store different classes array and show them in different sections. On the other hand, I also used a array, called headers, to store section headers' name. For example, in the "weekday" section, there are seven words, Sunday to Saturday, in the tableViewCell under this section. In the MainViewController:
-(void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *weekday=[[NSMutableArray alloc]init];
NSMutableArray *traffic=[[NSMutableArray alloc]init];
for (NSArray *sec_ary in listData) {
NSString *class=[[sec_ary valueForKey:#"vocabulary_list"]valueForKey:#"Class"];
if ([class isEqualToString:#"WEEKDAY"]) {
[weekday addObject:[[sec_ary valueForKey:#"vocabulary_list"]valueForKey:#"Vocabulary"]];
}else if ([class isEqualToString:#"TRAFFIC TOOLS"]){
[traffic addObject:[[sec_ary valueForKey:#"vocabulary_list"]valueForKey:#"Vocabulary"]];
}
sections=[[NSArray alloc ]initWithObjects:weekday,traffic,nil];
headers=[[NSArray alloc]initWithObjects:#"WEEKDAY",#"TRAFFIC TOOLS",nil];
}
In this App, I also implemented the navigation controller, which can bring user to view detail information in the didSelectRowAtIndexPath method. The codes are following
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
ContentViewController *content= [[ContentViewController alloc] initwithIndexPath:indexPath];
[delegate.navController1 pushViewController:content animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *TableIdentifier = #"tableidentifier"; /
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:TableIdentifier] autorelease];
}
cell.textLabel.text = (NSString*)[[self.sections objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
return cell;
}
In the ContentViewController:
-(void)viewDidLoad{
[super viewDidLoad];
AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
NSDictionary *voc_list=[delegate.vcblr objectAtIndex:index.row];
//extracting the voc_list dictionary to show infomation.....
}
I am wondering why each section will load the information from beginning in the voc_list. That is to say, the tableViewCell do not respond to the right detail content. Could anyone provide me with ideas to resolve it?
I am wondering why each section will load the information from beginning in the voc_list.
Because the code of your viewDidLoad method ignores index.section, paying attention to index.row alone. You need to decide on the index that you pass to delegate.vcblr based on both the section and the row; the exact calculation depends on the structure of your data, i.e. how many rows you have in each section.
Note : Using AppDelegate to share data among view controllers is not a good idea. Consider separating out your data in a separate model class, and make that class a singleton.

UITableView random crash with cell.contentview set

i am working on a uitableview and i am getting random crashes with when i use custom uiviewcontroller inside a uitableviewcell.
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(!cell){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
SuspectSalesResponse* r = [valueArray objectAtIndex:indexPath.row];
SuspectSalesCellViewController* scellView = [[SuspectSalesCellViewController alloc]initWithNibName:#"SuspectSalesCellViewController" bundle:nil cellData:r];
if(![cellViewArray containsObject:scellView])
[cellViewArray addObject:scellView];
[cell.contentView addSubview:scellView.view];
}
return cell;
This code sometimes work, sometimes it gives the folowing error:
* -[SuspectSalesHeaderViewController _parentModalViewController]: message sent to deallocated instance 0x8556880
i've tried keeping contentviews within an array (cellViewArray) but no luck i am still getting this error. What am i doing wrong?
Thanks for helping!
The problem is that you are not supposed to add view controllers inside table cells. You should try to change from UIViewController to UIView.
The exact reason for your crash is that you create a controller (which has a view) and you are adding the view to your cell, but the controller object is lost. When the view sends whatever notification to it's parent controller, the controller is already deallocated and there is where you get your bad access. This will be solved if you transform your SuspectSales~ to a UIView subclass
EDIT
To load a UIView (or any subclass) from a nib file, you must first create the xib, set the view's class to your class (you do it in the third tab on the interface builder).
After that, you can load it with this code:
Generic function in some utility class
+ (id)loadNibNamed:(NSString *)nibName ofClass:(Class)objClass {
if (nibName && objClass) {
NSArray *objects = [[NSBundle mainBundle] loadNibNamed:nibName owner:nil options:nil];
for (id currentObject in objects ){
if ([currentObject isKindOfClass:objClass])
return currentObject;
}
}
return nil;
}
In your class:
Subclass *view = [UtilityClass loadNibNamed:#"Subclass" ofClass:[Subclass class]];

Confusing syntax with custom UITableViewCell

I have found this code for a custom UITableViewCell :
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray* views = [[NSBundle mainBundle] loadNibNamed:#"MyCustomCell" owner:nil options:nil];
MyCustomCell *customCell = [[MyCustomCell alloc]init];
MyCustomCell.cellImage = [arrayImages objectAtIndex:indexPath.row];
for (UIView *view in views)
{
if([view isKindOfClass:[UITableViewCell class]])
{
cell = (MyCustomCell *)view;
}
}
}
and I could not figure how this specific part works: cell = (MyCustomCell *)view;
I wanted to change it for my previously created instance of MyCustomCell (customCell)... How could I do that?
Sometimes people will create a custom UITableViewCell using Interface Builder. This person is just loading their custom UITableViewCell subclass and assigning it to the cell. The line: cell = (MyCustomCell *)view; presumable works because MyCustomCell is a subclass of UITableViewCell.
This is just another technique for creating custom cells sometimes you'll see a similar thing done with tags.
First, it's iterating over a collection of UIViews, or UIView subclasses. It's storing each iteration's variable into a pointer called view.
It's then simply casting the current view variable to a type of MyCustomCell. Presumably MyCustomCell extends UIView, so this is legal.
This is useful if you want to use methods specific to MyCustomCell, as Xcode won't know they exist, if you don't explicitly Type Cast your object.

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: