Detail View from TableView, Parsing - objective-c

Can someone please help me, I looked everywhere to figure this out and nothing worked so far. I need to pass some data from table view to detail view and stick it into labels and Uiimage.
Data tableview is pulling comes from Parse database I created and seems to get pulled fine into the Tableview but I would like to use the same array that tableview is using for its data to fill out the detail view.
I am using 2 columns from parse to fill out this tableview Title and sub, and another tow columns to fill out the label and image. Here is my code so far. There is a bunch of variables that i was using in this code in DetailView
.h
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#interface BooksTableViewController : UITableViewController <UITableViewDelegate,NSObject >
{
NSArray * Booksarray;
}
#property (strong, nonatomic) IBOutlet UITableView *bookstableview;
#end
.m
#import "BooksTableViewController.h"
#import "BookDetailViewController.h"
#interface BooksTableViewController ()
#end
#implementation BooksTableViewController
#synthesize bookstableview;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self performSelector:#selector(RetrieveDatafromParse)];
// 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) RetrieveDatafromParse {
PFQuery * getbooks = [PFQuery queryWithClassName:#"BooksTableView"];
[getbooks findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if(!error) {
Booksarray =[[NSArray alloc] initWithArray: objects];
}
[bookstableview reloadData];
NSLog(#"%#",objects);
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (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 Booksarray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * CellIdentifier = #"Cell";
UITableViewCell * cell = [bookstableview dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell ==nil) {
cell = [[ UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"Cell"];
}
PFObject * tempObject = [Booksarray objectAtIndex:indexPath.row];
cell.textLabel.text = [tempObject objectForKey:#"Books"];
cell.detailTextLabel.text= [tempObject objectForKey:#"Code"];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
BookDetailViewController * detailVC=[[BookDetailViewController alloc] initWithNibName:#"BookDetailViewController" bundle:nil];
detailVC.BookImage.image=[Booksarray objectAtIndex:indexPath.row];
detailVC.bookDesc.text=[Booksarray objectAtIndex:indexPath.row];
detailVC.bookTitle.text=[Booksarray objectAtIndex:indexPath.row];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.destinationViewController isKindOfClass: [BookDetailViewController class]]) {
BookDetailViewController *destination = segue.destinationViewController;
SEL selector = NSSelectorFromString(#"SetFile:");
if ([destination respondsToSelector:selector]) {
NSIndexPath *indexPath = [self.bookstableview indexPathForCell:sender];
PFObject * object = [Booksarray objectAtIndex:indexPath.row];
PFFile *file = [object objectForKey:#"BooksTableView"];
[destination setValue:file forKey:#"file"];
}
}
}
#end
.h
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#interface BookDetailViewController : UIViewController <NSObject> {
}
#property (weak, nonatomic) IBOutlet UIImageView *BookImage;
#property (weak, nonatomic) IBOutlet UILabel *bookTitle;
#property (weak, nonatomic) IBOutlet UILabel *bookDesc;
#property (weak,nonatomic)PFFile *file;
#end
.m
#import "BookDetailViewController.h"
#import "BooksTableViewController.h"
#interface BookDetailViewController ()
#implementation BookDetailViewController
#synthesize BookImage,bookTitle,bookDesc,file,bookInfo,Picture,object2;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self performSelector:#selector(RetrieveObjectsFromParse)];
self.bookTitle.text = [self.file objectForKey:#"Books"];
self.BookImage.image = [self.file objectForKey:#"BookImage"];
self.bookDesc.text =[self.file objectForKey:#"BookDetails"];
}
-(void)RetrieveObjectsFromParse {
PFQuery * GetObjects = [PFQuery queryWithClassName:#"BooksTableView"];
[GetObjects findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if(!error) {
details =[[NSArray alloc] initWithArray: objects];
};
NSLog(#"%#",objects);
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end

Try this:
#1 create a segue from controller to controller:
#2 Give your segue an Id for example detailSegue.
#3 Perform the segue in didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self performSegueWithIdentifier:#"detailSegue" sender:sender];
}
#4 Implement the segue delegate:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Make sure your segue name in storyboard is the same as this line
if([segue.identifier isEqualToString:#"detailSegue"]){
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
BookDetailViewController *detailVC = (BookDetailViewController *)segue.destinationViewController;
detailVC.bookDesc.text=[Booksarray objectAtIndex:indexPath.row];
//I uncommented that because it looks like a typo, same value 3 times?
//detailVC.BookImage.image=[Booksarray objectAtIndex:indexPath.row];
//detailVC.bookTitle.text=[Booksarray objectAtIndex:indexPath.row];
}
}
If this is the log you get:
2014-03-21 15:06:20.151 BookStore[25539:90b]
BookIndex= { BookDetails = "Test
test"; BookImage = ""; Books = Languages; Code =
104; }
Then you need to do it like this instead:
detailVC.bookTitle.text=[[Booksarray objectAtIndex:indexPath.row]objectForKey:#"Books"];
detailVC.bookDesc.text= [[Booksarray objectAtIndex:indexPath.row]objectForKey:#"BookDetails"];
detailVC.BookImage.image=[[Booksarray objectAtIndex:indexPath.row]objectForKey:#"BookImage"];
Or to make it shorter:
NSArray *bookAtIndex = [Booksarray objectAtIndex:indexPath.row];
detailVC.bookTitle.text=[bookAtIndex objectForKey:#"Books"];
detailVC.bookDesc.text= [bookAtIndex objectForKey:#"BookDetails"];
detailVC.BookImage.image=[bookAtIndex objectForKey:#"BookImage"];
or even shorter
NSArray *bookAtIndex = Booksarray[indexPath.row];
detailVC.bookTitle.text= bookAtIndex[#"Books"];
detailVC.bookDesc.text= bookAtIndex[#"BookDetails"];
detailVC.BookImage.image= bookAtIndex[#"BookImage"];

Related

Best Pattern for multiple Popovers in Storyboard

I am writing an iPad application which will have several buttons that when clicked open a popover to a tableview. The user will choose a value, and the popover will be dismissed and the button't title will change.
I got this working with one Popover, and then wanted to add another. I want to write some good, clean reusable code.
My big hangup is with delegates. How many should there be? Should each popover have its own.
Root View Controller Header
#import <UIKit/UIKit.h>
#import "PopViewController1.h"
#import "PopViewController2.h"
#interface RootViewController : UIViewController <PopViewControllerDelegate,UIPopoverControllerDelegate>
// Properties for accessing the popover and its viewcontroller (1)
#property (strong, nonatomic) IBOutlet UIButton *btnOpenPopover1;
#property (strong, nonatomic) UIStoryboardPopoverSegue *pvcSegue1;
#property (strong, nonatomic) PopViewController1 *pvc1;
// Properties for accessing the popover and its viewcontroller (2)
#property (strong, nonatomic) IBOutlet UIButton *btnOpenPopover2;
#property (strong, nonatomic) UIStoryboardPopoverSegue *pvcSegue2;
#property (strong, nonatomic) PopViewController2 *pvc2;
#end
Root View Controller Method
#import "RootViewController.h"
#interface RootViewController ()
#end
#implementation RootViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[self setBtnOpenPopover1:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"segPop1"]) {
_pvcSegue1 = (UIStoryboardPopoverSegue *)segue;
_pvc1 = [segue destinationViewController];
[_pvc1 setDelegate:self];
} else ([[segue identifier] isEqualToString:#"segPop2"]); {
_pvcSegue2 = (UIStoryboardPopoverSegue *)segue;
_pvc2 = [segue destinationViewController];
//[_pvc2 setDelegate:self];
}
}
// PopViewControllerDelegate callback function
- (void)dismissPop:(NSString *)value {
[_btnOpenPopover1 setTitle:value forState:UIControlStateNormal];
[[_pvcSegue1 popoverController] dismissPopoverAnimated: YES]; // dismiss the popover
}
#end
PopViewController1.h
#import <UIKit/UIKit.h>
#protocol PopViewControllerDelegate;
#interface PopViewController1 : UITableViewController
#property (weak) id <PopViewControllerDelegate> delegate;
#property (strong, nonatomic) NSString *strPassedValue;
#property (nonatomic, strong) NSMutableArray *importantChoices;
#end
#protocol PopViewControllerDelegate <NSObject>
#required
- (void)dismissPop:(NSString *)value;
#end
PopViewController1 Method
#import "PopViewController1.h"
#interface PopViewController1 ()
#end
#implementation PopViewController1
- (id)initWithCoder:(NSCoder *)aDecoder
{
//Popover Choices
_importantChoices = [NSMutableArray array];
[_importantChoices addObject:#"Extremely Important"];
[_importantChoices addObject:#"Very Important"];
[_importantChoices addObject:#"Somewhat Important"];
[_importantChoices addObject:#"Not Very Important"];
[_importantChoices addObject:#"Not At All Important"];
self.clearsSelectionOnViewWillAppear = NO;
NSInteger rowsCount = [_importantChoices count];
NSInteger singleRowHeight = [self.tableView.delegate tableView:self.tableView
heightForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
NSInteger totalRowsHeight = rowsCount * singleRowHeight;
//Calculate how wide the view should be by finding how
//wide each string is expected to be
CGFloat largestLabelWidth = 0;
for (NSString *colorName in _importantChoices) {
//Checks size of text using the default font for UITableViewCell's textLabel.
CGSize labelSize = [colorName sizeWithFont:[UIFont boldSystemFontOfSize:20.0f]];
if (labelSize.width > largestLabelWidth) {
largestLabelWidth = labelSize.width;
}
}
//Add a little padding to the width
CGFloat popoverWidth = largestLabelWidth + 100;
//Set the property to tell the popover container how big this view will be.
self.contentSizeForViewInPopover = CGSizeMake(popoverWidth, totalRowsHeight);
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// 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;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)viewWillAppear: (BOOL)animated
{
}
- (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 [_importantChoices count];}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [_importantChoices objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
_strPassedValue = [_importantChoices objectAtIndex:indexPath.row];
[_delegate dismissPop:_strPassedValue];
}
#end
PopViewController2 Header
#import <UIKit/UIKit.h>
#protocol PopViewControllerDelegate;
#interface PopViewController2 : UITableViewController
#property (weak) id <PopViewControllerDelegate> delegate;
#property (strong, nonatomic) NSString *strPassedValue2;
#property (nonatomic, strong) NSMutableArray *importantChoices2;
#end
#protocol PopViewControllerDelegate <NSObject>
#required
- (void)dismissPop2:(NSString *)value;
#end
PopViewController2 Method
import "PopViewController2.h"
#interface PopViewController2 ()
#end
#implementation PopViewController2
- (id)initWithCoder:(NSCoder *)aDecoder
{
//Popover Choices
_importantChoices = [NSMutableArray array];
[_importantChoices addObject:#"Extremely Important"];
[_importantChoices addObject:#"Very Important"];
[_importantChoices addObject:#"Somewhat Important"];
[_importantChoices addObject:#"Not Very Important"];
[_importantChoices addObject:#"Not At All Important"];
self.clearsSelectionOnViewWillAppear = NO;
NSInteger rowsCount = [_importantChoices count];
NSInteger singleRowHeight = [self.tableView.delegate tableView:self.tableView
heightForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
NSInteger totalRowsHeight = rowsCount * singleRowHeight;
//Calculate how wide the view should be by finding how
//wide each string is expected to be
CGFloat largestLabelWidth = 0;
for (NSString *colorName in _importantChoices) {
//Checks size of text using the default font for UITableViewCell's textLabel.
CGSize labelSize = [colorName sizeWithFont:[UIFont boldSystemFontOfSize:20.0f]];
if (labelSize.width > largestLabelWidth) {
largestLabelWidth = labelSize.width;
}
}
//Add a little padding to the width
CGFloat popoverWidth = largestLabelWidth + 100;
//Set the property to tell the popover container how big this view will be.
self.contentSizeForViewInPopover = CGSizeMake(popoverWidth, totalRowsHeight);
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// 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;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)viewWillAppear: (BOOL)animated
{
}
- (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 [_importantChoices count];}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [_importantChoices objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
_strPassedValue = [_importantChoices objectAtIndex:indexPath.row];
[_delegate dismissPop:_strPassedValue];
}
#end
Any help or suggestions would be greatly appreciated!!!
Bryan
For reusable code, you only want one version of PopViewController. Your two versions look identical, so get rid of one. In InterfaceBuilder, set your buttons to all segue to a single PopViewController. Root View Controller, then, looks like this:
#property (strong, nonatomic) IBOutlet UIButton *btnOpenPopover1;
#property (strong, nonatomic) IBOutlet UIButton *btnOpenPopover2;
In prepareForSegue:, rather than segue to one version or another of PopViewController, just segue to your single version. Add a property to Root View Controller, to keep track of it (this replaces pvc1 and pvc2):
#property (strong, nonatomic) PopViewController* currentPopoverController;
You also need to keep track of which button is being edited, so add a property to your Root View Controller for that (note the weak reference):
#property (weak, nonatomic) IBOutlet UIButton* currentButton;
Set both of these in prepareForSegue:, so it looks like this:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
currentPopoverController = [segue destinationViewController];
[currentPopoverController setDelegate:self];
currentButton = (UIButton*) sender;
}
Now, you only need one delegate that looks like this:
- (void)dismissPop:(NSString *)value {
[currentButton setTitle:value forState:UIControlStateNormal];
[currentPopoverController dismissPopoverAnimated:YES];
}
I figured this out.
I needed to put in my segue in the h file, set that to the segue title, and then I added the segue property to the prepareForSegue method:
_segPopViewController = (UIStoryboardPopoverSegue *)segue;
Finally in the delegate I was able to put in this line:
[[_segPopViewController popoverController] dismissPopoverAnimated: YES];
And success!
Kudos to the original poster - you helped me a ton! I wish I could up vote you more than one!!!
Bryan

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.

Master - detail tableviews - not sure about how/where to do the IF-statement

In my app I´m using a master tableView with 3 cells, taken from a JSON. Each of these 3 cells will be connected to another tableView but Im not sure how to do this IF-statement.
Heres the .m for the master tableView. So far I only connected 1 detailView(tableView) to the master:
#import "GuideTableViewController.h"
#import "GuideDetailTableViewController.h"
#import <QuartzCore/QuartzCore.h>
#interface GuideTableViewController (){
NSArray *guide;
}
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property (weak, nonatomic) IBOutlet UIImageView *imgHeader;
#property (weak, nonatomic) IBOutlet UIButton *btnMap;
#property (weak, nonatomic) IBOutlet UIImageView *ImgTitle;
#end
#implementation GuideTableViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
//JSONmetod
- (void) loadJSON{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//code
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://dl.dropbox.com/u/100670549/test.json"]];
NSError *error;
if (data)
{
guide = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
for (NSDictionary *dictionary in guide){
NSLog([dictionary description]);
}
}else
{
NSLog(#"Could not load data");
}
dispatch_sync(dispatch_get_main_queue(), ^{
// code
[self.tableView reloadData];
});
});
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//Anropa json
[self loadJSON];
//set background
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background.jpg"]];
//rounded corners
[self.tableView.layer setCornerRadius:9.0];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//TableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 3;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
NSDictionary *dict = [guide objectAtIndex:indexPath.row];
cell.textLabel.text = [dict valueForKey:#"title"];
return cell;
}
//To detailView. Started with an IF here.
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:#"showStay"]){
GuideDetailTableViewController *tvc = [segue destinationViewController];
NSIndexPath *index = sender;
NSDictionary *dict = [guide objectAtIndex:index.row];
tvc.stay = dict;
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self performSegueWithIdentifier:#"showStay" sender:indexPath];
}
- (void) viewWillAppear:(BOOL)animated{
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.tableView.indexPathForSelectedRow];
//ta bort markeringen när man går tillbaka till master från detailView.
[cell setSelected:NO];
//Hide navbar
[self.navigationController setNavigationBarHidden:YES];
}
//Show navbar in detailView
-(void)viewWillDisappear:(BOOL)animated{
[self.navigationController setNavigationBarHidden:NO];
}
#end
Thanks in advance!
Your code is all right.
The if-statement is at the right place.
If you already linked your prototype cell to the detail view in the storyboard you don't need to implement tableView:DidSelectRowAtIndexPath:
prepareForSegue:sender: is called automaticaly.

tableView doesn't show anything

I'm sure my code is withour mistake, because I have two same tableViews and both with same code, same content and same design. But I don't understand why one of my tableViews is shown, and the other one isn't. I'm using Dynamic Prototype Content, Grouped Style and both tableViews are in container view in other ViewController. Here is code:
table.h
#import <UIKit/UIKit.h>
#interface table : UIViewController <UITableViewDataSource, UITableViewDelegate>
{
NSArray *tabledata;
NSIndexPath* checkedIndexPath;
}
#property (nonatomic, retain) NSArray *tabledata;
#property (nonatomic, assign) int number;
#property (nonatomic, retain) NSIndexPath* checkedIndexPath;
#property (strong, nonatomic) IBOutlet UITableView *tableView;
+(table*)instance;
#property (nonatomic) NSInteger selectedRow;
#end
table.m
#import "table.h"
#interface table ()
#end
#implementation table
#synthesize tabledata;
#synthesize tableView;
#synthesize checkedIndexPath;
#synthesize number;
+(InstrumentsI*)instance {
static table *statInst;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
statInst = [[table alloc] init];
});
return statInst;
}
#synthesize selectedRow;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
tabledata = [[NSArray alloc] initWithObjects:#"row1", #"row2", #"row3", nil];
self.selectedRow = 0;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - TableView Data Source methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [tabledata count];
}
- (UITableViewCell *)tableView:(UITableView *)tableview cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
cell = [tableview dequeueReusableCellWithIdentifier:#"identifer"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"identifer"];
}
cell.textLabel.text = [tabledata objectAtIndex:indexPath.row];
if (indexPath.row == self.selectedRow)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
#pragma mark TableView Delegate methods
- (void)tableView:(UITableView *)tableview didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[table instance].selectedRow = indexPath.row;
if (indexPath.row != self.selectedRow) {
self.selectedRow = indexPath.row;
}
[tableView reloadData];
}
- (void)viewDidUnload {
[self setTableView:nil];
[super viewDidUnload];
}
#end
Check if you have implemented all the delegates and datasource methods.
Also confirm that you have set your file's owner or controller as delegates and datasource.
Try to reload the tableview after loading the data, like:
- (void)viewDidLoad
{
[super viewDidLoad];
tabledata = [[NSArray alloc] initWithObjects:#"row1", #"row2", #"row3", nil];
self.selectedRow = 0;
[self.tableView reloadData];
}

Form sheet with custom split view like UITableView crash when scrolling

I have created a iPad app that has a settings form sheet. The form sheet is using two subviews for create a split view like display. The left (master) UITableView scrolls and launches fine. The error is coming in from when one of the master cells is selected and it displays a UITableView from a UITableViewController into the right(detail) view. It will display the UITableView but once it is scrolled the detail view crashes. Yes I have the list pulling from plist because I want these results be be accessed later in other places of the application.
this is the View Controller for the form sheet and delegate for Master View
.h file
#interface settingsViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>{
UITableView *mainTableView;
NSDictionary *mainSettingList;
NSArray *settingItems;
}
#property (weak, nonatomic) IBOutlet UINavigationBar *settingsNavigationBar;
#property (weak, nonatomic) IBOutlet UITableView *mainTableView;
#property (weak, nonatomic) IBOutlet UIView *borderView;
#property (strong, nonatomic) IBOutlet UIView *detailView;
.m file
#property (nonatomic, strong)NSDictionary *mainSettingList;
#property (nonatomic, strong)NSArray *settingItems;
#end
#implementation settingsViewController
#synthesize settingsNavigationBar = _settingsNavigationBar;
#synthesize mainTableView = _mainTableView;
#synthesize borderView = _borderView;
#synthesize settingItems, mainSettingList;
-(void)viewDidLoad{
[super viewDidLoad];
[self.detailView setFrame:CGRectMake(233, 0, 310, 620)];
[self.borderView setBackgroundColor:[UIColor lightGrayColor]];
[self.view addSubview:self.borderView];
[self.view addSubview:self.detailView];
}
- (IBAction)closePressed:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
-(NSDictionary *)mainSettingList{
if(!mainSettingList){
NSString *str_settingList = [[NSBundle mainBundle]pathForResource:#"settingsList" ofType:#"plist"];
mainSettingList = [NSDictionary dictionaryWithContentsOfFile:str_settingList];
self.mainSettingList = mainSettingList;
}
return mainSettingList;
}
-(NSArray *)settingItems{
if(!settingItems){
settingItems = [[self.mainSettingList allKeys]sortedArrayUsingSelector:#selector(compare:)];
self.settingItems = settingItems;
}
return settingItems;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.settingItems.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *wordsInSection = [self.mainSettingList objectForKey:
[self.settingItems objectAtIndex:section]];
return wordsInSection.count;
}
-(NSString *)nameAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *wordsInSection = [self.mainSettingList objectForKey:[self.settingItems objectAtIndex:indexPath.section]];
return [wordsInSection objectAtIndex:indexPath.row];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"AlumniListCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.textLabel.text = [self nameAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [self.settingItems objectAtIndex:section];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UINavigationController *nvc = [[UINavigationController alloc]init];
[nvc.view setFrame:CGRectMake(0,0, 310, 620)];
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;
if([cellText isEqualToString:#"Types of Jumps"]){
TypesOfJumps *toj = [[TypesOfJumps alloc]initWithNibName:#"TypesOfJumps" bundle:nil];
[nvc pushViewController:toj animated:YES];
}
[self.detailView addSubview:nvc.view];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:#"You selected %#!", cellText] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
return YES;
}
- (void)viewDidUnload {
[self setSettingsNavigationBar:nil];
[self setBorderView:nil];
[self setMainTableView:nil];
[self setSubViewNavigaionBar:nil];
[self setDetailView:nil];
[super viewDidUnload];
}
#end
UITableViewController called by cell pressed method
.h file
#interface TypesOfJumps : UITableViewController<UITableViewDataSource,UITableViewDelegate>{
NSDictionary *listJumps;
NSArray *typesJumps;
}
#property (strong, nonatomic) IBOutlet UITableView *tableView;
.m file
#interface TypesOfJumps ()
#property (strong, nonatomic)NSDictionary *listJumps;
#property (strong, nonatomic)NSArray *typesJumps;
#end
#implementation TypesOfJumps
#synthesize listJumps = _listJumps;
#synthesize typesJumps = _typesJumps;
#synthesize tableView = _tableView;
-(NSDictionary *)listJumps{
if(!listJumps){
NSString *str_settingList = [[NSBundle mainBundle]pathForResource:#"TypesOfJumps" ofType:#"plist"];
listJumps = [NSDictionary dictionaryWithContentsOfFile:str_settingList];
self.listJumps = listJumps;
}
return listJumps;
}
-(NSArray *)typesJumps{
if(!typesJumps){
typesJumps = [[self.listJumps allKeys]sortedArrayUsingSelector:#selector(compare:)];
self.typesJumps = typesJumps;
}
return typesJumps;
}
- (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.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.typesJumps.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *wordsInSection = [self.listJumps objectForKey:
[self.typesJumps objectAtIndex:section]];
return wordsInSection.count;
}
-(NSString *)nameAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *wordsInSection = [self.listJumps objectForKey:[self.typesJumps objectAtIndex:indexPath.section]];
return [wordsInSection objectAtIndex:indexPath.row];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"AlumniListCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.textLabel.text = [self nameAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [self.typesJumps objectAtIndex:section];
}