UITableView Delegate Assignment EXC_BAD_ACCESS - iphone

My iphone program has a Xib view with a tableview dropped in. I've subclassed UITableViewController and am trying to make the UITableView in the xib send it messages. The program crashes when I touch a tableview row.
It properly calls:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{}
and the cell.textLabel.text is assigned properly.
Interface snippet:
#interface PlayersDrawsViewController : UIViewController {
UITableView *uitableView;
PlayersToDrawTableViewController *pvc;
}
#property (nonatomic, retain) IBOutlet UITableView *uitableView;
#property (nonatomic, retain) IBOutlet PlayersToDrawTableViewController *pvc;
Implementation snippet:
- (void)viewDidLoad
{
// Setup TableView
if (pvc == nil) {
pvc = [[PlayersToDrawTableViewController alloc]
initWithNibName:#"PlayersToDrawTableViewController" bundle:nil];
/* works great, loads rows */
self.uitableView.dataSource = pvc.tableView.dataSource;
/* EXC_BAD_ACCESS when didSelectRowAtIndexPath is called */
//self.tableView.delegate = pvc;
}
}
My UITableViewController Subclass:
#interface PlayersToDrawTableViewController : UITableViewController
<UITableViewDelegate>
{
}
#end
How can I get the delegate hooked up so it doesn't crash sending messages?
I've read these threads and either I'm dense or they don't answer my question:
UITableView issue when using separate delegate/dataSource
UITableView superClass for delegate?
Getting “EXC_BAD_ACCESS” when accessing instance variable from within UITableView delegate method
didSelectRowAtIndexPath generates EXC_BAD_ACCESS while willSelectRowAtIndexPath works fine UITableView

If this line is crashing with EXC..:
self.tableView.delegate = pvc;
...did you hook up the tableView reference somewhere? In your code snippet "no" - but maybe you did in the NIB?

Related

Passing data between UITableViewCell and UITableViewController?

I created master details template project in xcode 4.6 and I added custom cell with 2 textfields. I also created new class which is subclass of UITableViewCell and inside this class I created outlets for text fields. When user types something NSMutableArray is updated and this works fine. Now I am wondering how to pass this array back to MasterViewController (UITableViewController) so that I can use this data to show calculations.
I tried using tutorials for delegates between UIViewControllers but I keep getting errors. Any help is appreciated.
You shouldn't keep data inside the UITableViewCell, as it breaks the MVC.
You need to get a reference of the UITextField on your cell. This is how I do in a login form:
I have a custom cell subclass called TextFieldCell, it has an outlet called textField, I want that my UITableViewController have references to these UITextFields.
First I open my storyboard, set the cell class to TextFieldCell and than connect the UITextField to cell textField outlet. Than I add this to the tableView:cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
(…)
if (indexPath.row == 0) {
// Sets the textField of the first cell as the loginTextField.
self.loginTextField = tCell.textField;
} else {
// Sets the textField of the second cell as the passwordTextField.
self.passwordTextField = tCell.textField;
}
tCell.textField.delegate = self;
(…)
}
Now I can access the value of my loginTextField and my passwordTextField. I do that on the tableView:cellForRowAtIndexPath: because that's when I'm creating the cell to add to the table view.
In your case you need to create Protocol:
I just Give Basic Idea for how to Create Protocol
Also Read This Question
#DetailViewController.h
#import <UIKit/UIKit.h>
#protocol MasterDelegate <NSObject>
-(void) getButtonTitile:(NSString *)btnTitle;
#end
#interface DetailViewController : MasterViewController
#property (nonatomic, assign) id<MasterDelegate> customDelegate;
#DetailViewController.m
if([self.customDelegate respondsToSelector:#selector(getButtonTitile:)])
{
[self.customDelegate getButtonTitile:button.currentTitle];
}
#MasterViewController.m
create obj of DetailViewController
DetailViewController *obj = [[DetailViewController alloc] init];
obj.customDelegate = self;
[self.navigationController pushViewController:reportTypeVC animated:YES];
and add delegate method in MasterViewController.m for get button title.
#pragma mark -
#pragma mark - Custom Delegate Method
-(void) getButtonTitile:(NSString *)btnTitle;
{
NSLog(#"%#", btnTitle);
}

Objective-C: Problems accessing objects in other UIViewControllers

So I have a Custom UITableViewCell that holds a reference to its containing view controller (the VC that has its table in it).
// MyCell.h
#import <UIKit/UIKit.h>
#import "RootViewController.h"
#interface MyCell : UITableViewCell
#property (nonatomic, strong) IBOutlet RootViewController *rootViewController;
-(IBAction)checkBoxClicked:(UIButton*)sender;
// MyCell.m
#implementation MyCell
#synthesize rootViewController = _rootViewController;
-(IBAction)checkBoxClicked:(UIButton*)sender
{
[self setCheckBoxChecked:!_checkBoxChecked];
[_rootViewController refreshVisibleViewForCellTagged:self.tag];
}
In my cell I have a button that changes a variable and then calls a function in my rootViewController. The method is actually called however when I try to access any object in the RootViewController inside of the refreshVisibleViewForCellTagged method they are are '0x0' / nil;
// RootViewController.h
#interface RootViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
#property (nonatomic, strong) IBOutlet UITableView *myTableView;
// RootViewController.m
- (void) refreshVisibleViewForCellTagged:(NSInteger)cellTag
{
UITableView *tableView = self.myTableView; // nil
NSIndexPath *indexPath = [self.myTableView indexPathForSelectedRow]; // nil
MyCell *selectedCell = (MyCell*)[self.myTableView cellForRowAtIndexPath:indexPath]; // nil
if (selectedCell.tag == cellTag) {
NSLog(#"Refresh one way.");
} else {
NSLog(#"Do something else.");
}
}
Can anyone shed some light as to why I cant access any objects/variables in the RootController from within the method 'refreshVisibleViewForCellTagged'?
Please and thank you!
** My big question is Why can't I access any objects when calling a method in a view controller From a different view controller. There is some great programming truth that I am not aware of here, is it a permissions issue? Im not using #class (forward classing) in this instance.
As #trojanfoe said, delegation is a better way to do it.
Instead of #import "RootViewController.h", it is better to adop delegation. Because UITableViewCell is a child and RootViewController is the parent view. You don't want the child to talk directly with the parent.
To adopt delegation:
in MyCell.h file
remove #import "RootViewController.h".
revise MyCell.h as follows:
#protocol MyCellDelegate; // if you need to have forward declaration
#interface MyCell : UITableViewCell
// #property (nonatomic, strong) IBOutlet RootViewController *rootViewController;
#property (nonatomic) id <MyCellDelegate> delegate;
#end
#protocol MyCellDelegate <NSObject>
- (void)refreshVisibleViewForCellTagged:(NSInteger)cellTag;
#end
in MyCell.m.
#synthesize delegate;
-(IBAction)checkBoxClicked:(UIButton*)sender {
[self setCheckBoxChecked:!_checkBoxChecked];
//[_rootViewController refreshVisibleViewForCellTagged:self.tag];
[self.delegate refreshVisibleViewForCellTagged:self.tag];
}
in RootViewController.h adopt the delegation of MyCell
#import "MyCell.h"
#interface RootViewController : UIViewController <MyCellDelegate>
in RootViewController.m.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = // your implementation
//assuming all your cells are of MyCell kind
// set RootViewController as the delegate of each cell
((MyCell *)cell).delegate = self;
return cell;
}
implement the delegate method in RootViewController.m.
- (void)refreshVisibleViewForCellTagged:(NSInteger)cellTag {
// whatever you have
}
P.S. The above codes are for illustration. I didn't run them. If some part doesn't work, let me know, and I'll revise it.
The reason those objects in RootViewController are nil in the way you call, is because you are not accessing the same instance of RootViewController. It is a different (new) instance and hence all objects are nil.
Ignore the fact that view controllers are even involved. What you have are OBJECTS, connected together in a certain pattern. Accessing data in another view controller is no different from accessing data in any other object. There's no "magic" with view controllers, other than they have a few standardized connections to other objects.
IMHO, this is a poor design. For starters, your cell shouldn't need a reference to the view controller that the table it's in is in (read that twice, it barely makes sense just because the very idea of it is confusing). You have a strong reference to this view controller. So what happens when the OS tries to deallocate your view controller? It will never be able to, because the table view cell as a strong reference to it, keeping its retain count at 1. The same situation holds true for the cell. You risk running into a retain cycle here. Generally, child views should have weak references to their parents.
But this isn't even really a true parents/child relationship. I would suggest instead an approach like this, which all occurs in your view controller that contains the table view:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Assuming you set a reuse identifier "cellId" in the nib for your table view cell...
MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:#"cellId"];
if (!cell) {
// If you didn't get a valid cell reference back, unload a cell from the nib
NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:#"MyCell" owner:nil options:nil];
for (id obj in nibArray) {
if ([obj isMemberOfClass:[MyCell class]]) {
// Assign cell to obj, and add a target action for the checkmark
cell = (MyCell *)obj;
[cell.checkMarkButton addTarget:self action:#selector(checkPressed:) forControlEvents:whateverEventYouWant];
break;
}
}
}
// Set the tag of the cell here, since we may get a different cell back from the reuse queue
cell.checkMarkButton.tag = indexPath.row;
return cell;
}
Now set up the method for the clicking of the checkmark button
- (void)checkPressed:(id)sender {
UIButton *checkmark = (UIButton *)sender;
// This will give you the row of the checked button
int checkedCellRow = checkmark.tag;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:checkedCellRow inSection:0];
// Now you can grab a reference to that cell if you need to
MyCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
}
This way, you keep all of the controller-related stuff in your controller class (i.e. how to handle the checkmark button being pressed), and you don't need to deal with this whackiness of referencing the view controller of your cell's table.
EDIT: I guess I should also help answer your questions...First of all, if you're saying that in your refreshVisibleViewForCell method, you're getting a nil value for self.myTableView, are you sure it is hooked up properly in IB? Even if it's hooked up, click the little x to unhook it and hook it up again to be sure. Also make sure you've #synthesized your myTableView property. Without seeing more code, an IB issue is my best guess as to why you're getting a nil value for tableView. A nil value here will result in a nil indexPath and selectedCell, also. As for your big question, you can access properties of objects within your view controller. Those properties can, of course, be objects. So in your example, if you have a tag property on selectedCell, you can access it from anywhere that you have a valid reference to selectedCell. If selectedCell is nil, the property will be nil. #class is better suited for header files. For instance, if you wanted to make your custom cell a property of your view controller, you might say:
#import <UIKit/UIKit.h>
#class MyCell;
#interface RootViewController : UIViewController
#property (nonatomic, strong) MyCell *cell;
#end
Then, in your implementation file, you would actually import MyCell.h. Giving the #class forward declaration just keeps you from having to import all of the details about the MyCell class in your header file. The header doesn't need to know about all of the properties and methods of MyCell, just that you intend on using it in the implementation file. So you #class in the header, #import in the implementation.
in RootViewController.h:
#interface RootViewController : UITableViewController <UITableViewDelegate>
in RootViewController.m:
- (void) refreshVisibleViewForCellTagged:(NSInteger)cellTag {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
MyCell *selectedCell = (MyCell*)[self.myTableView cellForRowAtIndexPath:indexPath]; // nil
etc...
I'm not seeing declarations of myTableView in your RootViewController. But if your RootViewController implements UITableViewController, you can use self.tableView to access the tableview. You don't need to keep a reference to it by yourself.
#RachelD, if your RootView is more complicated than just a UITableViewController consider using a separate class, such as RootTableViewController. Then in your RootView xib, create IBOutlet for RootTableViewController to reference it. Like this:
// RootTableViewController definition
#interface RootTableViewController : UITableViewController
{
}
// RootViewController definition
#interface RootViewController : UIViewController
{
RootTableViewController *table_c;
}
#property (nonatomic, retain) IBOutlet RootTableViewController *table_c;
Note that you need to drag an "Object" into the "Objects" section (for RootViewController) in the interface builder, and type RootTableViewController in the Custom Class section for this object. Right click this object, make sure its IBOutlet, view, 2 delegates are correctly set.
The reason why your myTableView is nil is because it's not properly initialized. I mean, if you don't use UITableViewController you are responsible for assigning it manually via interface builder or something.

Are there Anyone that use TableViewController without subclassing?

I am just curious. In IB, we can put a tableviewcontroller. However, as far as I know, we always subclass that tableview controller right? That way we can implement delegate, etc.
However, it seems that for some "default" behavior, IPhone intended tableviewcontroller to be used as is. Otherwise, why would IB let us put tableViewController like that?
Are there any sample code where people use tableViewController without subclassing?
Where does they implement things like what cells to draw, etc. then?
I guess the right answer of the question is that it's simply ridiculous to use a UITableViewController without sub classing. No body is doing it. Please correct me if I am wrong. I am just curious.
Whether you use a subclass of UITableViewController or UIViewController you need to set the data your table is going to display, otherwise, what's the point of a blank table? To achieve that you have to subclass and implement some methods. It's also a good idea to keep the delegate and the datasource in the same controller, unless the complexity really asks for different classes.
That being said, I always create my own table controllers as a subclass of UIViewController and implement the table controllers methods myself, because it gives you more flexibility. Matt Gallagher has several posts on how and why. See UITableView construction, drawing and management (revisited).
If you want to give it a try, create a subclass of UIViewController with a XIB and add the following sample code:
// interface
#import <UIKit/UIKit.h>
#interface SettingsVC : UIViewController <UITableViewDelegate, UITableViewDataSource>
#property (nonatomic, retain) IBOutlet UITableView *tableView;
#property (nonatomic, retain) NSMutableArray *array;
#end
// implementation
#synthesize tableView = _tableView;
#synthesize array = _array;
# pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.array count];
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
int row = [indexPath row];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [self.array objectAtIndex:row];
return cell;
}
Then add a UITableView object to the XIB, link the tableView of the controller to the UITableView object, and link the delegate and datasource of the UITableView to the controller.
No, this is not necessary to inherit your class with tableViewController. You can use table view by simply
putting TableViewController in xib.
and setting its delegate and datasourse to file's owner you can draw the table cells.
I don't think you can use a UITableViewController as is, it's like using a UIViewController without subclassing it : you can't set any inner mechanics.
But you can have a UITableView without using a UITableViewController.
Sure you can use UITableViewController without subclassing it.
Samplecode is very easy and straight forward.
For example like this:
- (IBAction)selectSomeOption:(id)sender {
UITableViewController *tableViewController = [[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];
tableViewController.tableView.dataSource = self;
tableViewController.tableView.delegate = self;
tableViewController.title = "Select some option";
[self.navigationController pushViewController:tableViewController animated:YES];
}
and the UITableViewDatasource and Delegate methods go into the same class.
Sure, if you like pain you could create a UIViewController in code and add a tableView on your own.
Or create a subclass for such an easy task.
The use of a non subclassed UITableViewController is sometimes convenient.

How can i display the data of the selected row from the tableview in the detail view in a splitview controller?

I've managed to read some values into a table view and display them in the Master View of a SplitViewController.
What I would like to do is to tap on a row of the Master View and display the details on the detailViewController but in a TableView.
When I tap on the row in the MasterView table, I can't seem to get the detail to populate the detailview TableView.
Any suggestions?
Thanks in advance.
Here's what you need to do:
Add an outlet to your master view controller which is a link to your detail view controller
Connect this outlet (either in Interface Builder or in code)
Add properties to your detail view for the values you're interested in displaying
in your implementation of tableView:didSelectRowAtIndexPath: retrieve the data for the selected row and set the corresponding properties in your detail view
Read this basic tutorial.
http://doronkatz.com/ipad-programming-tutorial-hello-world
Go through the sample code and see what you are doing wrong or missing
EDIT: its a tutorial on splitViewController.
may be this code is help for you
in table View .m file
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(self.dvController == nil){
DetailsViewController *viewControoler = [[DetailsViewController alloc]initWithNibName:#"detailsViewController" bundle:[NSBundle mainBundle]];
self.dvController = viewControoler;
[viewControoler release];
}
DocumentNavController *docObjNew = [appdelegate.noteArray objectAtIndex:indexPath.row];
[docObjNew hydrateDetailViewData];
//
dvcontroller.noteObj = docObjNew; //noteobj reference from in DetailsViewController.m file DocumentNavController *noteObj;
dvcontroller.currentindex = indexPath.row;
[self.navigationController pushViewController:self.dvController animated:YES];
self.dvController.title = [docObjNew noteTitle];
[self.dvController.noteTitelFiled setText:[docObjNew noteTitle]];
[self.dvController.notediscView setText:[docObjNew noteDisc]];
}
in table view .h file
#interface DocumentTableViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource> {
UITableView *documenttableView;
evernoteAppDelegate *appdelegate;
UINavigationController *navControll;
DetailsViewController *dvcontroller;
DocumentNavController *docNavContro;
//NSIndexPath *selectIndexPath;
}
#property (nonatomic, retain)DetailsViewController *dvController;
#property (nonatomic, retain)DocumentNavController *docNavContro;
#property (nonatomic, retain)UITableView *documenttableView;
in DetailsViewController.h file
UITextField *noteTitelFiled;
UITextView *notediscView;
DocumentNavController *noteObj;
#property (nonatomic, retain)IBOutlet UITextField *noteTitelFiled;
#property (nonatomic, retain)IBOutlet UITextView *notediscView;
#property (nonatomic, retain)DocumentNavController *noteObj;

Change the searchDisplayController table view style to grouped?

I have a searchDisplayController that searches a UITableView.
After entering the search terms, I can see another UITableView that contains the search results. However, I want this UITableView to be GROUPED, not PLAIN (like it is by default).
How do I do this?
This worked for me (iOS 5.0):
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
[self.searchController setValue:[NSNumber numberWithInt:UITableViewStyleGrouped]
forKey:#"_searchResultsTableViewStyle"];
If - like me - you think the plain TableView was way too ugly, you can also abandon the use of SearchDisplayController.
I just:
inserted in an empty View a searchBar and a TableView as we usually do for IBOutlet
selected the File's owner as delegate for both of them.
At the beginin the number of section is 0 ([myTab count]) then I used reloadData and this time myTab is populated by the result.
[self.resultTableView reloadData];
Here you can find all the method I used from the delegates
#interface MyViewController : UIViewController <UIApplicationDelegate, UISearchBarDelegate> {
IBOutlet UISearchBar *searchBar;
IBOutlet UITableView *resultTableView;
}
#property (nonatomic, retain) IBOutlet UISearchBar *searchBar;
#property (nonatomic, retain) IBOutlet UITableView *resultTableView;
//For your searchBar the 2 most important methods are
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBarClicked;
- (BOOL)searchBarTextDidEndEditing;
//For your TableView the most important methods are in my case:
//number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
//HEADERS
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
//different numbers of row by section
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
//the cells themselves
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
#end
After all, the simplest solution is often the best...
This works for me:
Create a class which extends UISearchDisplayController:
#interface RVSearchDisplayController : UISearchDisplayController
#end
#implementation RVSearchDisplayController
-(UITableView *) searchResultsTableView {
[self setValue:[NSNumber numberWithInt:UITableViewStyleGrouped]
forKey:#"_searchResultsTableViewStyle"];
return [super searchResultsTableView];
}
#end
Then add a UISearchDisplayController to your table using IB, and change its Custom Class to RVSearchDisplayController in Identity Inspector.
You could try to create a subclass of UISearchDisplayController and make searchResultsTableView searchable
in any .h file add:
#interface YourUISearchDisplayController : UISearchDisplayController {
UITableView * searchResultsTableView;
}
#property (nonatomic) UITableView * searchResultsTableView;
#end;
Then just use YourUISearchDisplayController instead od UISearchDisplayController.
Note: you might have to use (nonatomic, retain), (nonatomic, assign), or (nonatomic, copy). I'm not really sure
This is not possible as the searchResultsTableView property is readonly.
Overriding -searchResultsTableView won't work, because UISearchDisplayController accesses its table view instance variable directly, without calling the method.
The designated initializer for UISearchDisplayController appears to be a private method, -initWithSearchBar:contentsController:searchResultsTableViewStyle:, which sets the _searchResultsTableViewStyle instance variable. This instance variable is used in creating the search results table view. The public initializer calls this method, passing UITableViewStylePlain.
Directly calling the private designated initializer or setting the instance variable would likely get an application rejected from the App Store, so you might instead try overriding the public initializer and calling
[self setValue:[NSNumber numberWithInt:UITableViewStyleGrouped]
forKey:#"searchResultsTableViewStyle"];