Invalid index path for use with UITableView when selecting rows beyond a certain number - xcode

- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section
{
return #"Substitutes";
}
- (int)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
int cnt=[subArray count];
return [subArray count];
}
- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *visible = [tableView indexPathsForVisibleRows];
NSIndexPath *indexpath = (NSIndexPath*)[visible objectAtIndex:0];
if ((selectedIndexPath != nil) && (selectedIndexPath.row == indexPath.row)){
NSUInteger row = [indexPath row];
NSString *subtitle =[[subArray objectAtIndex:row] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *subDet =[[subDetArray objectAtIndex:row] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
int height = [self heightOfCellWithTitle:subtitle andSubtitle:subDet];
return(height < CONST_Cell_height ? CONST_Cell_height : height);
}
return 40.0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
static NSString *CellIdentifier = #"SearchCell";
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
if ((selectedIndexPath != nil) && (selectedIndexPath.row == indexPath.row)){
cell = [self CreateMultilinesCell:CellIdentifier];
cell.textLabel.text=[[subArray objectAtIndex:row] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
cell.detailTextLabel.text =[[subDetArray objectAtIndex:row] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
return cell;
} else {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.text=[[subArray objectAtIndex:row] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
cell.detailTextLabel.text =[[subDetArray objectAtIndex:row] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
return cell;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (selectedIndexPath == indexPath) {
selectedIndexPath = nil;
[table reloadData];
} else {
selectedIndexPath = indexPath;
//static NSString *CellIdentifier = #"Cell";
//UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//cell.textLabel.text=#"test";
//cell.detailTextLabel.text =#"det Test";
[table reloadData];
}
[self.table deselectRowAtIndexPath : indexPath animated : NO];
[tableView beginUpdates];
[tableView endUpdates];
}
i implemented table view using above code.when i selecting row no. 26 v or more it
expands on selection but doesn't contract on next click.& gives me error on scroll
NSInternalInconsistencyException', reason: 'Invalid index path for use with UITableView. Index paths passed to table view must contain exactly two indices specifying the section and row. Please use the category on NSIndexPath in UITableView.h if possible.'
code work smoothly for 25 rows. where i went wrong?

i got it finaly.:) selectedIndexpath gives garbage. i replace it by self.selectedIndexpath.
i didnt get why it do so on record no. 25 onwards.But this worked for me

Use like this
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag-1 inSection:0];
CGRect rectOfCellInTableView = [objTableView rectForRowAtIndexPath:indexPath];
CGRect rectOfCellInSuperview = [objTableView convertRect:rectOfCellInTableView toView:[objTableView superview]];

Related

Xcode - Segue issues

i've been trying to get a segue to work. I've written the following... but for some reason, the ...preparesegue... method doesnt fire. I've read other related posts but i cant get it to fire, and just as importantly, the variable i'm need isnt transferred.
m file:
#implementation CountryTableViewController
-(void) getData:(NSData *) data {
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
[self.tableView reloadData];
}
-(void) start {
NSURL *url = [NSURL URLWithString: URL];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getData:data];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self start];
}
- (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 [json count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellId = #"CellIdentifier";
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
if (!cell) {
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
}
NSDictionary *info = [json objectAtIndex:indexPath.row];
cell.TitleLabel.text = [info objectForKey:#"CountryName"];
cell.ReferenceLabel.text = [info objectForKey:#"id"];
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender tableView:(UITableView *)tableView {
//if ([segue.identifier isEqualToString:#"CountryToState"]) {
NSLog(#"TEST");
NSIndexPath *path = [self.tableView indexPathForSelectedRow];
TableViewCell *cell = (TableViewCell *)[tableView cellForRowAtIndexPath:path];
NSString *countryRef = [[cell ReferenceLabel] text];
TableViewControllerStates *TVCS = [segue destinationViewController];
TVCS.receivedReferenceNumber = countryRef;
//}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//TableViewCell *cell = (TableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
//NSString *countryRefNumber = [[cell ReferenceLabel] text];
[self performSegueWithIdentifier:#"CountryToState" sender:tableView];
}
h file
#import <UIKit/UIKit.h>
#define URL #"http://localhost/Rs.php"
#interface CountryTableViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource> {
NSMutableArray *json;
}
Any help appreciated; thank you in advance.

initWithStyle:UITableViewCellStyleSubtitle but subtitle not showing

Am trying to run the following code for a table with initWithStyle:UITableViewCellStyleSubtitle but the subtitle is not showing. Can you tell me what's wrong?
Thanks in advance!
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize listData;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray *array = [[NSArray alloc] initWithObjects:#"Sleepy", #"Sneezy", #"Bashful", #"Happy", #"Doc", #"Grumpy", #"Dopey", #"Thorin", #"Dorin", #"Nori", #"Ori", #"Balin", #"Dwalin", #"Fili", #"Kili", #"Oin", #"Gloin", #"Bifur", #"Bofur", #"Bombur", nil];
self.listData = array;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
self.listData = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [self.listData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:SimpleTableIdentifier];
}
UIImage *image = [UIImage imageNamed:#"star.png"];
cell.imageView.image = image;
NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
return cell;
if (row < 7)
cell.detailTextLabel.text = #"Mr. Disney";
else
cell.detailTextLabel.text = #"Mr.Tolkien";
}
#end
return cell;
Should be the last line. It returns before setting the detailTextLabel's text property.
Also, you should have received a warning from Xcode about "unreachable code."

Two warnings on - (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath method

Am getting two warnings on this method which I have commented out.
How can I fix this? Code below.
Thanks in advance.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize listData;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray *array = [[NSArray alloc] initWithObjects:#"Sleepy", #"Sneezy", #"Bashful", #"Happy", #"Doc", #"Grumpy", #"Dopey", #"Thorin", #"Dorin", #"Nori", #"Ori", #"Balin", #"Dwalin", #"Fili", #"Kili", #"Oin", #"Gloin", #"Bifur", #"Bofur", #"Bombur", nil];
self.listData = array;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
self.listData = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [self.listData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:SimpleTableIdentifier];
}
UIImage *image = [UIImage imageNamed:#"star.png"];
cell.imageView.image = image;
NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
if (row < 7)
cell.detailTextLabel.text = #"Mr. Disney";
else
cell.detailTextLabel.text = #"Mr.Tolkien";
return cell;
}
#pragma mark -
#pragma mark Table Delegate Methods
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
if (row == 0)
return nil; /* Incompatible pointer to integer conversion returning ‘void *' from a function with result type 'NSInteger' (aka 'int').*/
return indexPath; /* Incompatible pointer to integer conversion returning ‘NSIndexPath*_strong' from a function with result type 'NSInteger' (aka 'int').*/
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
NSString *rowValue = [listData objectAtIndex:row];
NSString *message = [[NSString alloc]
initWithFormat:#"You selected %#", rowValue];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Row selected"
message:message
delegate:nil
cancelButtonTitle:#"Yes I Did"
otherButtonTitles: nil];
[alert show];
}
#end
The function specifies it will return an NSInteger, returning nil or NSIndexPath will break that promise. What about:
NSInteger row = (NSInteger)[IndexPath row]; //casts the NSUInteger to NSInteger
if (row == 0)
{
return 0;
}
return row;

How to solve slow scrolling in UITableView - using the YouTube API

I'm working with the google YouTube API, and I'm using this code found here http://pastebin.com/vmV2c0HT
The Code that slows things down is this one here
cell.imageView.image = [UIImage imageWithData:data];
When I remove that code it scrolls smoothly. Any idea on how I can go about having it load the images from google but still scroll smoothly? I've read some of the answers on loading images in a different way, but I still can't figure out how I'll make that work with the code I'm using.
Any help will be appreciated.
Bellow is the full code.
#import "RootViewController.h"
#interface RootViewController (PrivateMethods)
- (GDataServiceGoogleYouTube *)youTubeService;
#end
#implementation RootViewController
#synthesize feed;
- (void)viewDidLoad {
NSLog(#"loading");
GDataServiceGoogleYouTube *service = [self youTubeService];
NSString *uploadsID = kGDataYouTubeUserFeedIDUploads;
NSURL *feedURL = [GDataServiceGoogleYouTube youTubeURLForUserID:#"BmcCarmen"
userFeedID:uploadsID];
[service fetchFeedWithURL:feedURL
delegate:self
didFinishSelector:#selector(request:finishedWithFeed:error:)];
[super viewDidLoad];
}
- (void)request:(GDataServiceTicket *)ticket
finishedWithFeed:(GDataFeedBase *)aFeed
error:(NSError *)error {
self.feed = (GDataFeedYouTubeVideo *)aFeed;
[self.tableView reloadData];
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[feed entries] count];
}
// 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.
GDataEntryBase *entry = [[feed entries] objectAtIndex:indexPath.row];
NSString *title = [[entry title] stringValue];
NSArray *thumbnails = [[(GDataEntryYouTubeVideo *)entry mediaGroup] mediaThumbnails];
cell.textLabel.text = title;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[thumbnails objectAtIndex:0] URLString]]];
cell.imageView.image = [UIImage imageWithData:data];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 100.0f;
}
- (void)dealloc {
[super dealloc];
}
- (GDataServiceGoogleYouTube *)youTubeService {
static GDataServiceGoogleYouTube* _service = nil;
if (!_service) {
_service = [[GDataServiceGoogleYouTube alloc] init];
[_service setShouldCacheDatedData:YES];
[_service setServiceShouldFollowNextLinks:YES];
}
// fetch unauthenticated
[_service setUserCredentialsWithUsername:nil
password:nil];
return _service;
}
#end
GCD is a wonderful thing. Here is what I do:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"youTubeCell";
UITableViewCell *cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell.
GDataEntryBase *entry = [[feed entries] objectAtIndex:indexPath.row];
NSString *title = [[entry title] stringValue];
NSArray *thumbnails = [[(GDataEntryYouTubeVideo *)entry mediaGroup] mediaThumbnails];
cell.textLabel.text = title;
// Load the image with an GCD block executed in another thread
dispatch_queue_t downloadQueue = dispatch_queue_create("image downloader", NULL);
dispatch_async(downloadQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[thumbnails objectAtIndex:0] URLString]]];
UIImage * image = [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = image;
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
[cell setNeedsLayout];
});
});
dispatch_release(downloadQueue);
return cell;
}
Scrolling is now super smooth. The only drawback is that when you scroll quickly, cells are re-used and sometimes the images change as new ones come in.

Grouped Table View

New to Xcode,
I have created a grouped table view,containing different amounts of rows in each section and I now do not know the best way to populate the cells with data then move on to the next view when the cell is pressed.
Please Help.
Thank you
you could try out this basic tutorial to see how you can populate your table..
http://blog.webscale.co.in/?p=150
and for performing action when a cell is pressed, you would basically need to do something like this in the didSelectRowAtIndexPath method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if( 0 == indexPath.row)
{
NSLog(#"first row selected");
if(patientView == nil)
patientView = [[PatientList alloc]init];
[self.navigationController pushViewController:patientView animated:YES];
}
This is just a very very basic example of what you want to do... playing a bit around with this would help you learn more...
**set in .h file**
#property(nonatomic, retain)NSArray *data;
#property(nonatomic, retain)NSArray *sections;
**in .m file view did load**
self.sections = [[NSArray alloc] initWithObjects:#"university",#"sabaragamuwa",#"Srilanka",nil];
self.data = [[NSArray alloc]initWithObjects:
[[NSArray alloc] initWithObjects:
#"CiS",
#"006",
#"07", nil],
[[NSArray alloc] initWithObjects:
#"cis",
#"006",
#"007", nil],
[[NSArray alloc] initWithObjects:
#"cis",
#"006",
#"07", nil],nil];
**addthoose**
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return [self.sections count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return [self.sections objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
// Return the number of rows in the section.
return [data count];}
**addalsooo**
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
SimpleTableIdentifier];
// Configure the cell...
if (cell == nil){
// Create the cell.
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier];
}
NSArray* dataArray = [data objectAtIndex:indexPath.section];
cell.textLabel.text = [dataArray objectAtIndex:indexPath.row];
cell.textLabel.textAlignment = UITextAlignmentRight;
cell.textLabel.textColor = [UIColor colorWithRed:0.0 green:139.0/255.0 blue:69.0/255.0 alpha:1.0];
UIImage *cellImage = [UIImage imageNamed:#"oranimCellIco.png"];
cell.imageView.image = cellImage;
return cell;}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray* dataArray = [data objectAtIndex:indexPath.section];
NSString *catgory= [dataArray objectAtIndex:indexPath.row];
if(catgory==#"cis")
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Answer Set"
message:#"Answer set as Yes Or No"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
else if(catgory==#"006")
{
answerviewcon *vc1=[self.storyboard instantiateViewControllerWithIdentifier:#"answerviewcon"];
[self presentViewController:vc1 animated:YES completion:nil];
}

Resources