Trying to solve a [DetailViewController setDataController:]: unrecognized selector sent to instance - objective-c

I have an Xcode Universal Storyboard project that is properly displaying data for the iPhone but does not display data for the iPad. I had initialized the data array using the code below.
It is working properly in the iPhone but does not display data in the iPad and gets the error:
-[DetailViewController setDataController:]: unrecognized selector sent to instance
This is the AppDelegate.m
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
MasterViewController *masterViewController = (MasterViewController *)[navigationController topViewController];
DataController *controller = [[DataController alloc] init];
masterViewController.dataController = controller;
splitViewController.delegate = (id)navigationController.topViewController;
} else {
// Create the data controller and pass it to the master view controller.
UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
MasterViewController *masterViewController = (MasterViewController *) [navigationController topViewController];
DataController *controller = [[DataController alloc] init];
masterViewController.dataController = controller;
}
The compiler is complaining about the DetailViewController here is that file.
#import "DetailViewController.h"
#import "Play.h"
#interface DetailViewController ()
#property (strong, nonatomic) UIPopoverController *masterPopoverController;
#end
#implementation DetailViewController
#synthesize masterPopoverController = _masterPopoverController;
#synthesize play;
#pragma mark -
#pragma mark View lifecycle
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// Scroll the table view to the top before it appears
[self.tableView reloadData];
[self.tableView setContentOffset:CGPointZero animated:YES];
//self.part = play.part;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
#pragma mark - Split view
- (void)splitViewController:(UISplitViewController *)splitController willHideViewController:(UITableViewController *)viewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController:(UIPopoverController *)popoverController
{
barButtonItem.title = NSLocalizedString(#"Trading Rules That Work", #"Trading Rules That Work");
[self.navigationItem setLeftBarButtonItem:barButtonItem animated:YES];
self.masterPopoverController = popoverController;
}
- (void)splitViewController:(UISplitViewController *)splitController willShowViewController:(UITableViewController *)viewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
// Called when the view is shown again in the split view, invalidating the button and popover controller.
[self.navigationItem setLeftBarButtonItem:nil animated:YES];
self.masterPopoverController = nil;
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// There are 2 sections, for rule, and media, in that order.
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//The number of rows varies by section.
NSInteger rows = 0;
switch (section) {
case 0:
// For part and date there is just one row.
rows = 1;
break;
case 1:
// For the media section, there are as many rows as there are media.
rows = [play.media count];
break;
default:
break;
}
return rows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.autoresizingMask = UIViewAutoresizingFlexibleHeight;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.font = [UIFont boldSystemFontOfSize:11];
cell.textLabel.numberOfLines = 13;
}
NSString *cellText = nil;
switch (indexPath.section) {
case 0:
cellText = play.part;
break;
case 1:
cellText = [play.media objectAtIndex:indexPath.row];
break;
default:
break;
}
cell.textLabel.text = cellText;
return cell;
}
#pragma mark -
#pragma mark Section header titles
/*
HIG note: In this case, since the content of each section is obvious, there's probably no need to provide a title, but the code is useful for illustration.
*/
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *title = nil;
switch (section) {
case 0:
title = NSLocalizedString(#"Video Description", #"Part section title");
break;
case 1:
title = NSLocalizedString(#"Media", #"Main Media section title");
break;
default:
break;
}
return title;
}
#end

When you do
object.property = value;
in Objective-C code, that's a short cut for:
[object setProperty:value];
Since you don't appear to have a dataController property, there's no setDataController selector.
So either:
declare a dataController property in your DetailViewController's .h then synthesize it in your implementation, or
create a setter and manually assign it to an instance variable.

You are getting this error because in your iPad storyboard you do not have the class set properly for your navigation controller's rootViewController. Make sure the class for that viewController is set to DataController in the Identity Inspector. You probably have this set correctly in your iPhone version storyboard, which is why you don't get the error when running the iPhone version.

Related

Trying to call a second table view with the items of de selected playlist in the first view

Maybe there's someone outthere who can help me fiure out my problem. I cant seem to display the playlistItems using cocoalibspotify. I have set up my playlistview and the first ableviewcontroller shows the playlist but when i try to call the items of the selected playlist I seem to get 0 numbersof row as my outputs show. the first view show how i pass the indexpath to the secondviewcontroller. the second script show my .h and .m files of the playlistitemsTavle view controller.
Overview.m - tableView with Playlists
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[playlistView deselectRowAtIndexPath:indexPath animated:NO];
playlistItemViewController *trailsController = [[playlistItemViewController alloc] initWithStyle:UITableViewStylePlain];
trailsController.currentPlaylist = [playlistArray objectAtIndex:indexPath.row];
//[[self navigationController] pushViewController:trailsController animated:YES];
[self getSongs];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showPlaylistItem"]) {
UITableViewCell *BasicCell = (UITableViewCell *) sender;
NSIndexPath *ip = [self.tableView indexPathForCell:BasicCell];
SPPlaylist *selectedPlaylist = [playlistArray objectAtIndex:ip.row];
playlistItemViewController *pivc = (playlistItemViewController *) segue.destinationViewController;
pivc.currentPlaylist = selectedPlaylist;
}
}
playlistitemsViewController.h -
#import <UIKit/UIKit.h>
#import "CocoaLibSpotify.h"
#import "Simple_PlayerAppDelegate.h"
#import "overViewController.h"
#interface playlistItemViewController : UITableViewController
{
UITableView *tableView;
}
#property (retain, nonatomic) IBOutlet UITableView *tableView;
#property (strong, readwrite, nonatomic) SPPlaylist *currentPlaylist;
#end
playlistViewController.m - this should call the playlist items
#import "playlistItemViewController.h"
#interface playlistItemViewController ()
#end
#implementation playlistItemViewController {
}
#synthesize currentPlaylist;
#synthesize tableView;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
NSLog(#"numberOfRowsInSection: %d",[[currentPlaylist items] count]);
return [[currentPlaylist items] count];
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"SubtitleCell";
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.textLabel.text = [[[currentPlaylist items] objectAtIndex:indexPath.row] valueForKey:#"name"];
return cell;
if (indexPath.row == 0) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"SubtitleCell"];
[[cell.backgroundView superview] bringSubviewToFront:cell.backgroundView];
cell.textLabel.text = #"";
}
else{
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"SubtitleCell"];
}
SPPlaylistItem * item = [[currentPlaylist items] objectAtIndex:[[currentPlaylist items]count] - indexPath.row];
cell.textLabel.text = [item.item name];
if (item.itemClass == [SPTrack class]) {
SPTrack * track = item.item;
cell.detailTextLabel.text = [track consolidatedArtists];
}
}
return cell;
}
#end
You need to wait for the playlist to load before the items are available.
Your playlist view controller needs to use SPAsyncLoading to load the playlist, something list this:
[SPAsyncLoading waitUntilLoaded:self.currentPlaylist timeout:kSPAsyncLoadingDefaultTimeout then:^(NSArray *loadedItems, NSArray *notloadedItems) {
[self.tableView reloadData];
}];
Playlist loading can take a while, so make sure you put up some "loading" UI. You'll also need to load the visible tracks in a similar manner before their names will be available.

Custom delegate/protocol didnt work like it should

I've been writing an app that has custom protocol to send the data from the child view to parent view the classes is
MainViewController
AddViewController (child to mainviewcontroller)
DaysViewController (child to addviewcontroller)
the custom protocol was declared in DaysViewController and implemented in AddViewController
AddViewController.h
#import <UIKit/UIKit.h>
#import "DaysViewController.h"
#import "Course.h"
#import "Student.h"
#interface AddViewController : UITableViewController<UIActionSheetDelegate,UIPickerViewDelegate,UIPickerViewDataSource,UIPickerViewAccessibilityDelegate,UITextFieldDelegate,DaysViewControllerDelegate>
{
NSArray *hoursarray;
UIActionSheet *aac;
IBOutlet UITextField *NameTx,*HoursTx,*DaysTx,*TimeTx;
Student *st;
Course *cc;
}
-(void) pickerDoneClick;
-(IBAction)fillTheOtherData;
#property (nonatomic ,strong) UIActionSheet *aac;
#end
AddViewController.m
#import "AddViewController.h"
#interface AddViewController ()
#end
#implementation AddViewController
#synthesize aac;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// 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;
//viewP.frame = CGRectMake(0, 154, 320, 205);
hoursarray = [[NSArray alloc]initWithObjects:#"2",#"3",#"4", nil];
[self.tableView setScrollEnabled:NO];
[DaysTx setEnabled:NO];
[TimeTx setEnabled:NO];
[HoursTx setKeyboardType:UIKeyboardTypeDecimalPad];
cc = [[Course alloc]init];
//UITapGestureRecognizer *tapgr = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(tapped:)];
//[self.view addGestureRecognizer:tapgr];
}
-(void)tapped:(UITapGestureRecognizer *)tap
{
[self.view endEditing:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [hoursarray count];
}
//-(IBAction)addCourse
//{
// [UIView beginAnimations:#"view" context:nil];
// [UIView setAnimationDuration:1];
// viewP.frame = CGRectMake(0, 500, 320, 205);
// [UIView commitAnimations];
//
//}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [hoursarray objectAtIndex:row];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 3)
{
aac = [[UIActionSheet alloc]initWithTitle:#"How many ?" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil, nil];
UIPickerView *picker = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 44, 0, 0)];
picker.delegate = self;
picker.dataSource = self;
UIToolbar *pickerToolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
[pickerToolBar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc]init];
UIBarButtonItem *flexspace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexspace];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(pickerDoneClick)];
[barItems addObject:doneBtn];
[pickerToolBar setItems:barItems animated:YES];
[aac addSubview:pickerToolBar];
[aac addSubview:picker];
[aac showInView:self.view];
[aac setBounds:CGRectMake(0, 0, 320, 464)];
}
else if (indexPath.row == 2)
{
DaysViewController *days = [self.storyboard instantiateViewControllerWithIdentifier:#"Days"];
days.delegate = self;
[self.navigationController pushViewController:days animated:YES];
}
}
-(void) pickerDoneClick
{
[aac dismissWithClickedButtonIndex:0 animated:YES];
}
-(void)chooseDays:(DaysViewController *)controller withArray:(NSArray *)theDaysArray
{
NSLog(#"I'm # chooseDays method");
NSLog(#"Before the add !!");
NSLog(#"chooseDays Method and the array is %#",theDaysArray);
cc.days = [NSMutableArray arrayWithObject:theDaysArray];
NSLog(#"After the add");
NSLog(#"chooseDays Method and the array is %#",cc.days);
// [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)cancelChooseDays:(DaysViewController *)controller
{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(IBAction)fillTheOtherData
{
cc.name = NameTx.text;
cc.hour = [HoursTx.text integerValue];
NSLog(#"The name is %# and the hour credit is %d",cc.name,cc.hour);
}
#end
DaysViewController.h
#import <UIKit/UIKit.h>
#import "Course.h"
#class DaysViewController;
#protocol DaysViewControllerDelegate <NSObject>
#required
-(void)chooseDays:(DaysViewController *)controller withArray:(NSArray *)theDaysArray;
-(void)cancelChooseDays:(DaysViewController *)controller;
#end
#interface DaysViewController : UITableViewController
{
Course *courseDays;
NSArray *days;
NSMutableArray *dayChosen;
}
#property (nonatomic,weak) id<DaysViewControllerDelegate> delegate;
-(IBAction)done:(id)sender;
-(IBAction)cancel:(id)sender;
#end
DaysViewController.m
#import "DaysViewController.h"
#interface DaysViewController ()
#end
#implementation DaysViewController
#synthesize delegate;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// 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;
days = [[NSArray alloc]initWithObjects:#"Saturday",#"Sunday",#"Monday",#"Teusday",#"Wednesday",#"Thursday",#"Friday", nil];
dayChosen = [[NSMutableArray alloc]init];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
// Return the number of rows in the section.
return [days count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"DaysCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"DaysCell"];
}
cell.textLabel.text = [days objectAtIndex:indexPath.row];
return cell;
}
-(IBAction)done:(id)sender
{
//Course *course = [[Course alloc]init];
//[course.days addObject:dayChosen];
//NSArray *daysArray = [NSArray arrayWithObject:dayChosen];
NSLog(#"The Days are %#",dayChosen);
[self.delegate chooseDays:self withArray:dayChosen];
[self dismissViewControllerAnimated:YES completion:nil];
}
-(IBAction)cancel:(id)sender
{
[self.delegate cancelChooseDays:self];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[dayChosen addObject:[days objectAtIndex:indexPath.row]];
NSLog(#"Days are %#",dayChosen);
}
#end
MainViewController has a button that take me to AddViewController and AddViewController has same button that takes me to DaysViewController , all the views has a UITableView .
what I want to do is when I send the data from DaysViewController to AddViewController to put it in an array and dismiss the view AddViewController should show up but instead MainViewController shows and this is what I dont want it to be.
AddViewController and DaysViewController have a UINavigationController but MainViewController doesn't.
Thank you in advance.
Okay, I think I know what your problem is. In your cancel function, try and switch this line of code:
[self dismissViewControllerAnimated:YES completion:nil];
With this line of code:
[self.navigationController popViewControllerAnimated:YES];
Let me know if that helps.

What are some reasons why custom UITableViewCells might work in iOS 6 but not iOS 5?

I am having a ton of trouble trying to get a table view to work on my iPhone. The weird thing is that it seems to work completely fine on my iOS simulator (i.e., I can add an entry to an array, and that entry shows up in my table view). However, when I try to add an entry when using my iOS device, the codes breaks on the line dequeueReusableCellWithIdentifier:. I've checked for capitalization inconsistencies, name inconsistencies, have reimplemented prepareForReuse in the custom UITableViewCell subclass, have tried defining fields in my UITableViewCell subclass using IBOutlets v. tags, and perhaps a few more things but none have worked.
This questions is tangentially related to my previous question: Debugging strategies when UITableView's cells don't load?
The tough part about programming is always knowing which question to ask, so I apologize if it turns out I am asking the wrong questions.
UPDATE 6: Problem Is Custom Layout For UITableViewCell On iOS 5
I tested using a subclass of UITableViewCell and UITableViewCell with a custom layout. Using a subclass of UITableViewCell with style UITableViewCellStyleDefault does work on both iOS 5 and iOS 6 iPhone simulator. However, using a generic UITableViewCell with a custom style crashes on iOS 5 but not iOS 6. Interestingly, I don't see a declaration for a custom UITableViewCellStyle in the documentation for UITableViewCell...
UPDATE 5: iOS 5 v. 6 + Custom UITableViewCell Subclass?
Hello: Continued testing today and it appears that it is an issue between how iOS 5 and 6 treat custom UITableViewCell subclasses. No solution yet :(
UPDATE 4: iOS 5 v. iOS 6?
So all I've been able to notice is that this seems to be an issue with iOS 5 versus iOS 6. When testing on iOS 6 using line GlassboxCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier] the code below works. However, neither that line nor GlassboxCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath] work in iOS 5. Any ideas? I somehow got it to work exactly once by changing the identifier to protocell.
UPDATE 3: I now use GitHub!
Here is the relevant repo: https://github.com/kenmhaggerty/Glassbox
UPDATE 2: More Observations
So I had added in #synthesize tableView = _tableView because I read in a response somewhere that it might help, but I now realize that it stopped my data from loading in my table view even when running on the iOS simulator. Commenting out that line of code returns the code back to how I describe it above: it works just fine on the iOS simulator but breaks on line dequeueReusableCellWithIdentifier: with no specified error, just Thread 1: breakpoint 1.1.
UPDATE 1: Relevant Code
GlassboxTableViewController.h
//
// GlassboxTableViewController.h
// Glassbox
//
// Created by Ken M. Haggerty on 10/22/12.
// Copyright (c) 2012 Ken M. Haggerty. All rights reserved.
//
#pragma mark - // NOTES (Public) //
#pragma mark - // IMPORTS (Public) //
#import <UIKit/UIKit.h>
#pragma mark - // PROTOCOLS //
//#protocol GlassboxTableViewDatasource <NSObject>
//#property (nonatomic, weak) NSMutableArray *arrayOfPlayers;
//#end
#pragma mark - // DEFINITIONS (Public) //
#interface GlassboxTableViewController : UITableViewController
#property (nonatomic, strong) NSMutableArray *arrayOfPlayers;
- (IBAction)addPlayer:(UIBarButtonItem *)sender;
//#property (nonatomic, strong) id <GlassboxTableViewDatasource> datasource;
#end
GlassboxTableViewController.m
//
// GlassboxTableViewController.m
// Glassbox
//
// Created by Ken M. Haggerty on 10/22/12.
// Copyright (c) 2012 Ken M. Haggerty. All rights reserved.
//
#pragma mark - // NOTES (Private) //
#pragma mark - // IMPORTS (Private) //
#import "GlassboxTableViewController.h"
#import "GlassboxCell.h"
#import "Player.h"
#import <MobileCoreServices/MobileCoreServices.h>
#pragma mark - // DEFINITIONS (Private) //
#define SIDEBAR_WIDTH_PERCENT 0.75
#interface GlassboxTableViewController () <UITableViewDataSource, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
//#property (nonatomic, weak) IBOutlet UITableView *tableView;
- (void)setup;
#end
#implementation GlassboxTableViewController
#pragma mark - // SETTERS AND GETTERS //
#synthesize arrayOfPlayers = _arrayOfPlayers;
#synthesize tableView = _tableView;
//#synthesize datasource = _datasource;
- (void)setArrayOfPlayers:(NSMutableArray *)arrayOfPlayers
{
_arrayOfPlayers = arrayOfPlayers;
}
- (NSMutableArray *)arrayOfPlayers
{
if (!_arrayOfPlayers) _arrayOfPlayers = [[NSMutableArray alloc] init];
// [_arrayOfPlayers addObject:[[Player alloc] initWithUsername:#"Ken H.:"]];
return _arrayOfPlayers;
}
#pragma mark - // INITS AND LOADS //
- (void)setup
{
self.tableView.dataSource = self;
self.tableView.delegate = self;
}
- (id)initWithStyle:(UITableViewStyle)style
{
NSLog(#"[initWithStyle]");
self = [super initWithStyle:style];
if (self) {
[self setup];
}
return self;
}
- (void)viewDidLoad
{
NSLog(#"[viewDidLoad]");
[super viewDidLoad];
[self setup];
// 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;
}
//- (void)viewDidAppear:(BOOL)animated
//{
// [super viewDidAppear:animated];
// [self.view setFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width*SIDEBAR_WIDTH_PERCENT, self.view.frame.size.height)];
//}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - // PUBLIC FUNCTIONS //
- (IBAction)addPlayer:(UIBarButtonItem *)sender
{
[self alertAddPlayer];
}
#pragma mark - // PRIVATE FUNCTIONS //
- (void)alertAddPlayer
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Add New Player" message:#"Please type player name:" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK",nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
alert.tag = 1;
[alert show];
}
- (void)alertInvalidPlayer
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Invalid Name" message:#"Please type another name:" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK",nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
alert.tag = 1;
[alert show];
}
- (void)alertAddPhoto
{
NSLog(#"[TEST] alertAddPhoto");
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
if ([mediaTypes containsObject:(NSString *)kUTTypeImage])
{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.delegate = self;
imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePickerController.allowsEditing = YES;
// imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceFront;
// imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
imagePickerController.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeImage];
// [self presentViewController:imagePickerController animated:YES completion:nil];
imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceFront;
[self presentModalViewController:imagePickerController animated:YES];
return;
}
}
NSLog(#"[TEST] No camera available");
[self.tableView reloadData];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
if (!image) image = [info objectForKey:UIImagePickerControllerOriginalImage];
if (image)
{
[[self.arrayOfPlayers lastObject] setPhoto:[[UIImageView alloc] initWithImage:image]];
}
[self dismissImagePicker];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissImagePicker];
}
- (void)dismissImagePicker
{
// [self dismissViewControllerAnimated:YES completion:^{
// [self.tableView reloadData];
// }];
[self dismissModalViewControllerAnimated:YES];
[self.tableView reloadData];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) NSLog(#"Cancel tapped");
else
{
if (alertView.tag == 1)
{
if (buttonIndex == 1)
{
if ([[[alertView textFieldAtIndex:0] text] length] != 0)
{
[self.arrayOfPlayers addObject:[[Player alloc] initWithUsername:[[alertView textFieldAtIndex:0] text]]];
[self alertAddPhoto];
}
else [self alertInvalidPlayer];
}
}
}
}
#pragma mark - // PRIVATE FUNCTIONS (Miscellaneous) //
// TableView data source //
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
//#warning Potentially incomplete method implementation.
// // Return the number of sections.
// return 0;
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// return self.datasource.arrayOfPlayers.count;
return self.arrayOfPlayers.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"New Cell";
// GlassboxCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
GlassboxCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.name.text = [[self.arrayOfPlayers objectAtIndex:indexPath.row] username];
cell.action.text = #"LOADED SUCCESSFULLY";
cell.time.text = #"Just now";
cell.photo = [[self.arrayOfPlayers objectAtIndex:indexPath.row] photo];
// [((UILabel *)[cell viewWithTag:1]) setText:[[self.arrayOfPlayers objectAtIndex:indexPath.row] username]];
// [((UILabel *)[cell viewWithTag:2]) setText:#"has been added."];
// [((UILabel *)[cell viewWithTag:3]) setText:#"Just now"];
// [((UIImageView *)[cell viewWithTag:4]) setImage:[[[self.arrayOfPlayers objectAtIndex:indexPath.row] photo] image]];
[cell.contentView setFrame:CGRectMake(cell.contentView.frame.origin.x, cell.contentView.frame.origin.y, cell.contentView.frame.size.width, 120)];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
// TableView delegate //
- (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];
*/
}
#end
Let me know if I should post more.
(Your github project does not compile (Player.h/Player.m missing), so it is difficult to reproduce the issue.)
But I noticed that "Use Autolayout" is on in the MainStoryboard file. Autolayout works only on iOS 6 and later, not on iOS 5!
Please post your code. I can advice you to leave the xib files for uitableviewcell and try again. Do you use one kind of cell? or you use few different style?
===== ANSWER =====
When you create cell GlassboxCell *cell and use dequeueReusableCellWIthIdentifier you need check if cell is allocated.
// use dequeueReusableCellWithIdentifier for init cell
if (cell == nil){
cell = [[[GlassboxCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:yourIdentifier]] autorelease];
}
//rest your code for init properties for cell
ok man try to use this function instead of yours.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"NewCell";
GlassboxCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[GlassboxCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.name.text = [[self.arrayOfPlayers objectAtIndex:indexPath.row] username];
cell.action.text = #"LOADED SUCCESSFULLY";
cell.time.text = #"Just now";
cell.photo = [[self.arrayOfPlayers objectAtIndex:indexPath.row] photo];
[cell.contentView setFrame:CGRectMake(cell.contentView.frame.origin.x, cell.contentView.frame.origin.y, cell.contentView.frame.size.width, 120)];
return cell;
}
I think I found the problem...at least it works on my project.
When you make a UITableViewController class with an older version of Xcode (say 4), the generated code for cellForRowAtIndexPath is this:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
But when you make a UITableViewController with Xcode 4.5.2 (mine), the generated code for cellForRowAtIndexPath is this:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
So in my case all I did was remove the "forIndexPath:indexPath" portion and it works!
(This is my first answer ever so please be gentle if I screwed up something)

Tabbed ios application with multiple table views

I'm using XCode 4.2 and testing my build on iPad 5.0.
I started building an application using the standard Tabbed application in XCode and then added code to have 2 uitableviews inside the first tab.
It compiles, but the table data does not load into the view.
App delegate.h:
#interface dmbAppDelegate : UIResponder <UIApplicationDelegate, UITabBarControllerDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) UITabBarController *tabBarController;
#end
AppDelegate.m:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
UIViewController *viewController1 = [[[dmbFirstViewController alloc] initWithNibName:#"dmbFirstViewController" bundle:nil] autorelease];
UIViewController *viewController2 = [[[dmbSecondViewController alloc] initWithNibName:#"dmbSecondViewController" bundle:nil] autorelease];
self.tabBarController = [[[UITabBarController alloc] init] autorelease];
self.tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, nil];
NSLog(#"Loading first tab view from app delegate...");
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
FirstViewController.h:
#interface dmbFirstViewController : UIViewController {
ReservationsTable *reservationsController;
WaitlistTable *waitlistController;
IBOutlet UITableView *reserveTable;
IBOutlet UITableView *waitlistTable;
}
FirstViewController.m:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSLog(#"FirstView Controller - View Loading Started");
[reserveTable setDataSource:reservationsController];
[waitlistTable setDataSource:waitlistController];
NSLog(#"FirstView Controller - Loading Table Views..");
[reserveTable setDelegate:reservationsController];
[waitlistTable setDelegate:waitlistController];
reservationsController.view = reservationsController.tableView;
waitlistController.view = waitlistController.tableView;
NSLog(#"FirstView Controller - View Loading Finished");
}
Both the tables have a .h and .m with the standard table methods implemented. I also added 2 tables in the first view nib file and linked them to the file owner.
Update:
ReserveTable.h:
#interface WaitlistTable : UITableViewController <UITableViewDataSource, UITableViewDelegate>{
NSMutableArray *waitlistitems;
}
ReserveTable.m:
- (void)viewDidLoad
{
NSLog(#"View Did Load - Wait List Table");
waitlistitems = [[NSMutableArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"6",#"8",#"9",#"10",#"11",#"12",#"13",#"14",#"15",#"16",#"17",nil] retain];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
NSLog(#"Inside number of section for Wait List table...");
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"Inside numberofRows for Wait List table...");
// Return the number of rows in the section.
return [waitlistitems count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Inside cell for row at index path for Wait List table...");
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
cell.textLabel.text = [NSString stringWithFormat:#"1.%#" ,[waitlistitems objectAtIndex:indexPath.row]];
return cell;
}
Thoughts?
Change your viewDidLoad to this:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
reservationsController = [[ReservationsTable alloc] init];
waitlistController = [[WaitlistTable alloc] init];
NSLog(#"FirstView Controller - View Loading Started");
[reserveTable setDataSource:reservationsController];
[waitlistTable setDataSource:waitlistController];
NSLog(#"FirstView Controller - Loading Table Views..");
[reserveTable setDelegate:reservationsController];
[waitlistTable setDelegate:waitlistController];
NSLog(#"FirstView Controller - View Loading Finished");
}
basically, you are never initializing your tableViewControllers (I guess that is the name of both of them, I would change their names to something like "WaitlistTableViewController" and "ReservationsTableViewController", but that is just me.) Also, setting the 'tableView' to the 'view' is unnecessary.
Or even better, initialize them in the init method for your dmbFirstViewController.
Or just use dmbFirstViewController like this:
dmbFirstViewController.h:
#interface dmbFirstViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
ReservationsTable *reservationsController;
WaitlistTable *waitlistController;
IBOutlet UITableView *reserveTable;
IBOutlet UITableView *waitlistTable;
NSMutableArray *waitlistitems;
NSMutableArray *reserveitems;
}
dmbFirstViewController.m:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
waitlistitems = [[NSMutableArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"6",#"8",#"9",#"10",#"11",#"12",#"13",#"14",#"15",#"16",#"17",nil] retain];
NSLog(#"FirstView Controller - View Loading Started");
[reserveTable setDataSource:self];
[waitlistTable setDataSource:self];
NSLog(#"FirstView Controller - Loading Table Views..");
[reserveTable setDelegate:self];
[waitlistTable setDelegate:self];
NSLog(#"FirstView Controller - View Loading Finished");
}
- (void)viewDidAppear:(BOOL)animated
{
[reserveTable reloadData];
[waitlistTable reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
NSLog(#"Inside number of section for Wait List table...");
if(tableView == waitlistTable)
{
//Return sections for waitlistTable
return 1;
}else{
//Return sections for reservedTable
return 1;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(tableView==waitlistTable)
{
NSLog(#"Inside numberofRows for Wait List table...");
// Return the number of rows in waitlistTable section.
return [waitlistitems count];
}else{
// Return the number of rows in reservedTable section.
return [reserveditems count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView == waitlistTable)
{
NSLog(#"Inside cell for row at index path for Wait List table...");
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
cell.textLabel.text = [NSString stringWithFormat:#"1.%#" ,[waitlistitems objectAtIndex:indexPath.row]];
return cell;
} else {
//Create cell for reservedTable Cell
.....
return cell;
}
}
You'll have to finish off the part about reservedTable cells, I didn't have that code. Plus, I guessed on the items array for reservedTable and did not initialize it.
I think in your firstViewController you should push the views.
Assuming that reserveTable is your main table, push it like so
[self.view addSubView:reserveTable];
Also, did you import the ReserveTable.h to your firstViewController?
If yes, you should initialize the table there though.
But what i suggest, though, is to transform the firstViewController in a tableViewController, editing the App Delegate and the firstViewController.h and m, and from there initialize the table (even adding the other one too). So that would be easier!

TableView is delegated, populates but wont group

I am having a weird problem and i couldn`t find a solution (or something similar).
The thing is, my UITableView Populates with initial info (for testing), but no matter what i do i can't seem to put it to grouped style (i can select it on the UI but it wont show)
I initially started a TabBar project and added a third navigationController view in the tabs.
#import <UIKit/UIKit.h>
#interface RootViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource> {
NSMutableArray *tableData;
}
#property (nonatomic, retain) NSMutableArray *tableData;
-(void)initTableData;
#end
This is the header, and as you can see it has nothing out of the ordinary. The following code is inside the .m file of the header i just posted(ill only be posting uncommented code:
#synthesize tableData;
-(void)initTableData
{
tableData = [[NSMutableArray alloc] init];
[tableData addObject:#"Cidade"];
[tableData addObject:#"Veículo"];
[tableData addObject:#"Ano"];
[tableData addObject:#"Valor"];
[tableData addObject:#"Cor"];
[tableData addObject:#"Combustível"];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Busca";
UIBarButtonItem *_backButton = [[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStyleDone target:nil action:nil];
self.navigationItem.backBarButtonItem = _backButton;
[self initTableData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return 6;
}
// 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...
cell.textLabel.text = [tableData objectAtIndex:[indexPath row]];
return cell;
}
- (void)dealloc {
[tableData release];
[super dealloc];
}
Nothing out of the ordinary again as you can see...
Any idea of what may be causing this? I tried
- (id)initWithStyle:(UITableViewStyle)style {
// Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
self = [super initWithStyle:UITableViewStyleGrouped];
if (self) {
// Custom initialization.
}
return self;
}
because i don't know what else to do. (also didn't worked)
Again, i got the delegate and datasource set to File`s Owner.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Set the tab bar controller as the window's root view controller and display.
self.window.rootViewController = self.tabBarController;
RootViewController *rvc = [[RootViewController alloc] initWithStyle: UITableViewStyleGrouped];
[self.window makeKeyAndVisible];
return YES;
}
As you have modified the - (id)initWithStyle:(UITableViewStyle)style initializer to return a UITableView with a grouped style, do you call this initializer when you initialize the RootViewController?
RootViewController *rvc = [[RootViewController] alloc] initWithStyle: UITableViewStyleGrouped];
Grouped tables respond to the sections. You only have 1 section listed so you will only see the 1 group. Try and add a 2nd tableData for the 2nd group and return 2 sections. You will also have to split the data in your -cellForRowAtIndexPath by section as well to make sure the data goes to the right section.
if (indexpath.section == 0) {
// first section and first tableData
}
if (indexpath.section == 1) {
// second section and second tableData
}