My TableView crashes when I make the run App - ios

I state that in my app I'm using Parse.com for storing and managing data.
In my tableview I have introduced two different custom cells. A is displayed if there is an image and the other hand is displayed if the image is not present.
Now everything seems to work but when I go to make the application run the Tableview crash reporting this error:
2013-11-22 15:36:34.256 UniGo![17186:70b]
Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:],/SourceCache/UIKit_Sim/UIKit-2903.23/UITableView.m:6246**
Can you explain where I'm wrong?
- (void)viewDidLoad {
[super viewDidLoad];
self.FFTableView.delegate = self;
self.FFTableView.dataSource = self;
CellaSelezionata = -1;
}
-(void)viewDidAppear:(BOOL)animated {
[self QueryForPost];
}
-(void)QueryForPost {
PFQuery *QueryForFriend=[PFQuery queryWithClassName:FF_AMICIZIE_CLASS];
[QueryForFriend whereKey:FF_AMICIZIE_A_USER equalTo:[PFUser currentUser]];
[QueryForFriend whereKey:FF_AMICIZIE_STATO equalTo:#"Confermato"];
[QueryForFriend includeKey:FF_AMICIZIE_DA_USER];
PFQuery *QueryYES = [PFQuery queryWithClassName:FF_POST_CLASS];
[QueryYES whereKey:FF_POST_FLASH_POST_BOOLEANVALUE equalTo:[NSNumber numberWithBool:YES]];
[QueryYES whereKey:FF_POST_SCELTI equalTo:[PFUser currentUser]];
PFQuery *normalPostByFriends = [PFQuery queryWithClassName: FF_POST_CLASS];
[normalPostByFriends whereKey: FF_POST_FLASH_POST_BOOLEANVALUE equalTo: [NSNumber numberWithBool: NO]];
[normalPostByFriends whereKey: FF_POST_UTENTE matchesKey:FF_AMICIZIE_DA_USER inQuery:QueryForFriend];
PFQuery *normalPostByUser = [PFQuery queryWithClassName:FF_POST_CLASS];
[normalPostByUser whereKey:FF_POST_FLASH_POST_BOOLEANVALUE equalTo: [NSNumber numberWithBool: NO]];
[normalPostByUser whereKey:FF_POST_UTENTE equalTo: [PFUser currentUser]];
PFQuery *query = [PFQuery orQueryWithSubqueries:#[QueryYES,normalPostByFriends,normalPostByUser]];
[query includeKey:FF_POST_UTENTE];
[query orderByDescending:FF_CREATEDAT];
[query findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
if (!error) {
ArrayforPost = [[NSMutableArray alloc] init];
for (PFObject *object in results) {
[ArrayforPost addObject:object];
}
[self.FFTableView reloadData];
}
}];
}
-(CGFloat)valoreAltezzaCella:(NSInteger)index {
PFObject *objectPost = [ArrayforPost objectAtIndex:index];
NSString *text = [objectPost objectForKey:#"Testo"];
CGSize MAX = CGSizeMake(230, 10000);
UIFont *FONT = [UIFont systemFontOfSize:14];
CGSize altezzaLabel = [text boundingRectWithSize:MAX options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:FONT }context:nil].size;
return altezzaLabel.height;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [ArrayforPost count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
PFObject *ObjectPost = [ArrayforPost objectAtIndex:indexPath.row];
// FIRST CUSTOM CELL
if (![ObjectPost objectForKey:FF_POST_IMMAGINE]) {
static NSString *IdentificazioneCella = #"CellPost";
FFCustomCellTimelineSocial * Cella = (FFCustomCellTimelineSocial *)[self.FFTableView dequeueReusableCellWithIdentifier:IdentificazioneCella];
if (Cella == nil) {
Cella = [[FFCustomCellTimelineSocial alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:IdentificazioneCella ];
}
Cella.backgroundCell.layer.cornerRadius = 2.0f;
Cella.backgroundCell.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
Cella.backgroundCell.layer.borderWidth = 1.0f;
Cella.backgroundCell.autoresizingMask = UIViewAutoresizingFlexibleHeight;
Cella.BackgroundText.layer.cornerRadius = 2.0f;
Cella.BackgroundText.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
Cella.BackgroundText.layer.borderWidth = 0.0f;
Cella.BackgroundText.autoresizingMask = UIViewAutoresizingFlexibleHeight;
Cella.TimeBackground.layer.cornerRadius = 2.0f;
Cella.TimeBackground.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
Cella.TimeBackground.layer.borderWidth = 1.0f;
Cella.ViewTestataCell.layer.cornerRadius = 2.0f;
Cella.ViewTestataCell.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
Cella.ViewTestataCell.layer.borderWidth = 1.0f;
Cella.FFImmagineUtente.layer.masksToBounds = YES;
Cella.FFImmagineUtente.layer.cornerRadius = 20.0f;
Cella.FFImmagineUtente.contentMode = UIViewContentModeScaleAspectFill;
Cella.FFTestoUtenteLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0f];
NSString *text = [ObjectPost objectForKey:FF_POST_TEXT];
Cella.FFTestoUtenteLabel.text = text;
[Cella.FFTestoUtenteLabel setLineBreakMode:NSLineBreakByTruncatingTail];
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd MMM"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
Cella.DataCorrente.text = dateString;
NSString *NomeUser = [[ObjectPost objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_NOMECOGNOME];
Cella.FFNomeUtenteLabel.text = NomeUser;
NSString *ImmagineUtente = [[ObjectPost objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_FOTOPROFILO];
Cella.FFImmagineUtente.file = (PFFile *)ImmagineUtente;
[Cella.FFImmagineUtente loadInBackground];
if (CellaSelezionata == indexPath.row) {
CGFloat AltezzaLabel = [self valoreAltezzaCella: indexPath.row];
Cella.FFTestoUtenteLabel.frame = CGRectMake(Cella.FFTestoUtenteLabel.frame.origin.x, Cella.FFTestoUtenteLabel.frame.origin.y, Cella.FFTestoUtenteLabel.frame.size.width, AltezzaLabel); }
else {
Cella.FFTestoUtenteLabel.frame = CGRectMake(Cella.FFTestoUtenteLabel.frame.origin.x, Cella.FFTestoUtenteLabel.frame.origin.y, Cella.FFTestoUtenteLabel.frame.size.width, 55);
}
PFObject *rowObject = [ArrayforPost objectAtIndex:indexPath.row];
if([[rowObject objectForKey:FF_POST_FLASH_POST_BOOLEANVALUE ] boolValue]) {
Cella.FlashPostImg.image = [UIImage imageNamed:#"FFNotificaFlash"];
}
else {
Cella.FlashPostImg.image = [UIImage imageNamed:#" "]; }
return Cella;
}
else {
// SECOND CUSTOM CELL
static NSString *IdentificazioneCellaIMG = #"CellIMG";
FFCustomCellWithImage * CellaIMG = (FFCustomCellWithImage * )[self.FFTableView dequeueReusableCellWithIdentifier:IdentificazioneCellaIMG];
CellaIMG = (FFCustomCellWithImage * )[self.FFTableView dequeueReusableCellWithIdentifier:IdentificazioneCellaIMG];
if (CellaIMG == nil) {
CellaIMG = [[FFCustomCellWithImage alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:IdentificazioneCellaIMG ];
}
NSString *FotoPostSocial = [ObjectPost objectForKey:FF_POST_IMMAGINE];
CellaIMG.FotoPost.file = (PFFile *)FotoPostSocial;
[CellaIMG.FotoPost loadInBackground];
CellaIMG.backgroundCell.layer.cornerRadius = 2.0f;
CellaIMG.backgroundCell.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
CellaIMG.backgroundCell.layer.borderWidth = 1.0f;
CellaIMG.backgroundCell.autoresizingMask = UIViewAutoresizingFlexibleHeight;
CellaIMG.TimeBackground.layer.cornerRadius = 2.0f;
CellaIMG.TimeBackground.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
CellaIMG.TimeBackground.layer.borderWidth = 1.0f;
CellaIMG.ViewTestataCell.layer.cornerRadius = 2.0f;
CellaIMG.ViewTestataCell.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
CellaIMG.ViewTestataCell.layer.borderWidth = 1.0f;
CellaIMG.FotoProfilo.layer.masksToBounds = YES;
CellaIMG.FotoProfilo.layer.cornerRadius = 20.0f;
CellaIMG.FotoProfilo.contentMode = UIViewContentModeScaleAspectFill;
CellaIMG.TestoPost.font = [UIFont fontWithName:#"Helvetica" size:14.0f];
NSString *text = [ObjectPost objectForKey:FF_POST_TEXT];
CellaIMG.TestoPost.text = text;
[CellaIMG.TestoPost setLineBreakMode:NSLineBreakByTruncatingTail];
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd MMM"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
CellaIMG.DataPost.text = dateString;
NSString *NomeUser = [[ObjectPost objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_NOMECOGNOME];
CellaIMG.NomeUtente.text = NomeUser;
NSString *ImmagineUtente = [[ObjectPost objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_FOTOPROFILO];
CellaIMG.FotoProfilo.file = (PFFile *)ImmagineUtente;
[CellaIMG.FotoProfilo loadInBackground];
if (CellaSelezionata == indexPath.row) {
CGFloat AltezzaLabel = [self valoreAltezzaCella: indexPath.row];
CellaIMG.TestoPost.frame = CGRectMake(CellaIMG.TestoPost.frame.origin.x, CellaIMG.TestoPost.frame.origin.y, CellaIMG.TestoPost.frame.size.width, AltezzaLabel);
}
else {
CellaIMG.TestoPost.frame = CGRectMake(CellaIMG.TestoPost.frame.origin.x, CellaIMG.TestoPost.frame.origin.y, CellaIMG.TestoPost.frame.size.width, 75);
}
return CellaIMG;
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; {
if (CellaSelezionata == indexPath.row) {
//SPAZIO INTERNO VERSO IL BASSO QUANDO APRI LA CELLA
return [self valoreAltezzaCella:indexPath.row] + 60 * 2;
}
else {
//GRANDEZZA CELLA PRIMA DI APRIRE
return 155 + 10 * 2;
}
}
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self valoreAltezzaCella:indexPath.row] > 65) {
return indexPath;
} else {
return nil;
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (CellaSelezionata == indexPath.row) {
CellaSelezionata = -1;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
return;
}
if (CellaSelezionata >= 0) {
NSIndexPath *previousPath = [NSIndexPath indexPathForRow:CellaSelezionata inSection:0];
CellaSelezionata = indexPath.row;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:previousPath] withRowAnimation:UITableViewRowAnimationFade];
}
CellaSelezionata = indexPath.row;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

dequeueReusableCellWithIdentifier - can return you nil
You need to check that and create a cell if that happens:
FFCustomCellTimelineSocial * Cella = (FFCustomCellTimelineSocial *)[self.FFTableView dequeueReusableCellWithIdentifier:IdentificazioneCella];
if (Cella == nil) {
Cella = [[[FFCustomCellTimelineSocial alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
}

Related

my scrolling through UITableView is somewhat choppy, how can i make it smooth?

Scrolling through the table is somewhat a bit choppy and stutters when scrolling.
Is there any improvements i can make to make it smooth?
here's my cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
UITableViewCell *cellEmpty;
if ([tableView isEqual:self.categoryTableView]) {
NSString *CellIdentifierCategory = #"categoryCell";
UITableViewCell *categoryCell = [self.categoryTableView dequeueReusableCellWithIdentifier:CellIdentifierCategory];
if (categoryCell == nil) {
categoryCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifierCategory];
}
else{
categoryCell.textLabel.text = [_categoryTableArray objectAtIndex:indexPath.row];
return categoryCell;
}
}
if ([tableView isEqual:self.tableView]) {
if (indexPath.section == self.objects.count) {
UITableViewCell *cell = [self tableView:tableView cellForNextPageAtIndexPath:indexPath];
UILabel *loadLabel = (UILabel *)[cell viewWithTag:1];
if (!self.isLoading) {
loadLabel.text = #"The End of Space";
self.tableView.tableFooterView = nil;
}
cell.userInteractionEnabled = NO;
return cell;
}
NSString *CellIdentifier = #"PhotoCell";
InterestsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[InterestsCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
else{
PFUser *user = [object objectForKey:#"userTookPhoto"];
dispatch_async(dispatch_get_main_queue(), ^{
cell.companyLogo.layer.cornerRadius = cell.companyLogo.frame.size.width / 2;
cell.companyLogo.clipsToBounds = YES;
});
[cell.productImageView setUserInteractionEnabled:YES];
[cell.priceLabel setUserInteractionEnabled:YES];
UITapGestureRecognizer *tapForImage = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleProductImageTap:)];
tapForImage.cancelsTouchesInView = YES;
tapForImage.numberOfTapsRequired = 1;
[cell.productImageView addGestureRecognizer:tapForImage];
UITapGestureRecognizer *tapForPrice = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleProductImageTap:)];
tapForPrice.cancelsTouchesInView = YES;
tapForPrice.numberOfTapsRequired = 1;
[cell.priceLabel addGestureRecognizer:tapForPrice];
cell.productImageView.tag = indexPath.section;
cell.productImageView.file = (PFFile *)object[#"image"];
[cell.productImageView loadInBackground:^(UIImage * _Nullable image, NSError * _Nullable error) {
} progressBlock:^(int percentDone) {
NSLog(#"float value: %f",percentDone * 0.01);
dispatch_async(dispatch_get_main_queue(), ^{
[cell.progressView setProgress:percentDone * 0.01 animated:YES];
});
if (percentDone == 100) {
[cell.progressView setHidden:YES];
}
}];
dispatch_async(dispatch_get_main_queue(), ^{
cell.productTitle.text = object[#"titleOfPhoto"];
});
[cell.companyLogo setUserInteractionEnabled:YES];
UITapGestureRecognizer *tapGesture1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(segueCompanyProfile)];
tapGesture1.numberOfTapsRequired = 1;
[cell.companyLogo addGestureRecognizer:tapGesture1];
if (user[#"profileImage"]) {
cell.companyLogo.file = (PFFile *)user[#"profileImage"];
[cell.companyLogo loadInBackground];
}
else{
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *image = [UIImage imageNamed:#"defaultBrandLogo.png"];
cell.companyLogo.image = image;
});
}
dispatch_async(dispatch_get_main_queue(), ^{
[cell.companyLabelButton setTitle:user.username forState:UIControlStateNormal];
cell.companyLabelButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
cell.companyLabelButton.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
});
[cell.companyLabelButton addTarget:self action:#selector(segueCompanyProfile) forControlEvents:UIControlEventTouchUpInside];
NSNumber *price = object[#"PriceOfPhoto"];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *numberAsString = [numberFormatter stringFromNumber:price];
NSString *priceLabelText = [NSString stringWithFormat:#"%#",numberAsString];
dispatch_async(dispatch_get_main_queue(), ^{
cell.priceLabel.text = priceLabelText;
});
// UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, cell.productTitle.frame.origin.y + cell.productTitle.frame.size.height + 10, self.view.frame.size.width - 30, 2)];
// line.backgroundColor = [UIColor groupTableViewBackgroundColor];
// [cell.cardView addSubview:line];
cell.likeButtonOutlet.delegate = self;
cell.likeButtonOutlet.sectionIndex = indexPath.section;
NSArray *likesArray = object[#"likesBy"];
if (likesArray.count > 0) {
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSString *groupingSeparator = [[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator];
[formatter setGroupingSeparator:groupingSeparator];
[formatter setGroupingSize:3];
[formatter setAlwaysShowsDecimalSeparator:NO];
[formatter setUsesGroupingSeparator:YES];
NSString *formattedString = [formatter stringFromNumber:[NSNumber numberWithFloat:likesArray.count]];
dispatch_async(dispatch_get_main_queue(), ^{
cell.likeCountLabel.text = formattedString;
});
}
else{
dispatch_async(dispatch_get_main_queue(), ^{
cell.likeCountLabel.text = nil;
});
}
if (likesArray.count > 0) {
for (NSString *likes in likesArray) {
if ([likes isEqualToString:[PFUser currentUser].objectId]) {
dispatch_async(dispatch_get_main_queue(), ^{
[cell.likeButtonOutlet setSelected:YES];
});
}
else{
dispatch_async(dispatch_get_main_queue(), ^{
[cell.likeButtonOutlet setSelected:NO];
});
}
}
}
else{
dispatch_async(dispatch_get_main_queue(), ^{
[cell.likeButtonOutlet setSelected:NO];
});
}
}
return cell;
}
return cellEmpty;
}

Parse Pagination loadNextPage 2nd Page Loads Twice

In my Parse app, I have Pagination enabled, and for testing purposes, objects per page set to 5. When I run the app I get this in my TableView
1
2
3
4
5
Load More
After clicking Load More the entire table looks like:
1
2
3
4
5
6
7
8
9
10
6
7
8
9
10
Clicking Load More after this will add the set of 11-15 twice. What is going on?
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
// The className to query on
self.parseClassName = #"Prayers";
// Whether the built-in pull-to-refresh is enabled
self.pullToRefreshEnabled = YES;
// Whether the built-in pagination is enabled
self.paginationEnabled = YES;
// The number of objects to show per page
self.objectsPerPage = 5;
}
return self;
}
- (PFQuery *)queryForTable {
PFQuery *query = [PFQuery queryWithClassName:#"Prayers"];
// If no objects are loaded in memory, we look to the cache first to fill the table
// and then subsequently do a query against the network.
if (self.objects.count == 0) {
query.cachePolicy = kPFCachePolicyCacheThenNetwork;
}
[query orderByDescending:#"createdAt"];
return query;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
object:(PFObject *)object
{
static NSString *CellIdentifier = #"Cell";
Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[Cell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
self.theObject = object;
BOOL anony = [object[#"Anonymous"] boolValue];
cell.profileName.text = object[#"Title"];
cell.contentLabel.text = object[#"Request"];
cell.firstName = object[#"FirstName"];
cell.lastName = object[#"LastName"];
cell.iostoken = object[#"DeviceID"];
cell.request = object[#"Title"];
cell.prayerObject = object;
PFFile *thumbnail = object[#"ProfilePic"];
cell.profilePic.image = [UIImage imageNamed:#"AppIcon60x60#2x.png"];
/*[cell.commentButton addTarget:self action:#selector(didTapCommentButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[cell.commentButton setTitle:#"Share" forState:UIControlStateNormal];
[cell.commentButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[cell.commentButton setTitleColor:[UIColor greenColor] forState:UIControlStateHighlighted];*/
[thumbnail getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
UIImage *thumbnailImage = [UIImage imageWithData:imageData];
UIImageView *thumbnailImageView = [[UIImageView alloc] initWithImage:thumbnailImage];
cell.profilePic.image = thumbnailImage;
}];
NSString *dates = object[#"dateMade"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM_dd_yyyy"];
NSDate *datefromstring = [formatter dateFromString:dates];
NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:#"MMM dd, yyyy"];
cell.dateLabel.text = [formatter2 stringFromDate:datefromstring];
UIFont *cellFont = [UIFont fontWithName:#"Verdana-Bold" size:15];
UIFont *cellFont2 = [UIFont fontWithName:#"Verdana-Bold" size:12];
return cell;
}
- (PFObject *)objectAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == self.objects.count) {
return nil;
} else {
return [super objectAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]];
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
PFObject *object = [self objectAtIndexPath:indexPath];
if (object == nil) {
// Return a fixed height for the extra ("Load more") row
return 70;
} else {
NSLog(#"%lu", (unsigned long)[self.objects count]);
PFObject *entry = [self.objects objectAtIndex:indexPath.row];
NSString *commentString = entry[#"Request"];
NSString *nameString = #"";
NSLog(#"%#", commentString);
return [Cell heightForCellWithContentString:(NSString *)commentString] +25 ;
}
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[super tableView:tableView didSelectRowAtIndexPath:indexPath];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if (indexPath.row == self.objects.count && self.paginationEnabled) {
// Load More Cell
NSLog(#"Load More");
[self loadNextPage];
}
-(PFQuery *)queryForTable {
...
...
...
//Always trigger a network request.
[tableQuery setCachePolicy:kPFCachePolicyNetworkOnly];
//If no objects are loaded in memory, we look to the cache first to fill the table and then subsequently do a query against the network.
if(self.objects.count == 0) {
[tableQuery setCachePolicy: kPFCachePolicyCacheThenNetwork];
}
...
...
...
return tableQuery;
}

Parse Pagination Not Working

In my app, I use Parse. I have it set up like this:
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
// The className to query on
self.parseClassName = #"Prayers";
// Whether the built-in pull-to-refresh is enabled
self.pullToRefreshEnabled = YES;
// Whether the built-in pagination is enabled
self.paginationEnabled = YES;
// The number of objects to show per page
self.objectsPerPage = 20;
}
return self;
}
- (PFQuery *)queryForTable {
PFQuery *query = [PFQuery queryWithClassName:#"Prayers"];
// If no objects are loaded in memory, we look to the cache first to fill the table
// and then subsequently do a query against the network.
if (self.objects.count == 0) {
query.cachePolicy = kPFCachePolicyCacheThenNetwork;
}
[query orderByDescending:#"createdAt"];
return query;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
object:(PFObject *)object
{
static NSString *CellIdentifier = #"Cell";
Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[Cell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
self.theObject = object;
BOOL anony = [object[#"Anonymous"] boolValue];
if (!anony) {
NSString *names = [[object[#"FirstName"] stringByAppendingString:#" "] stringByAppendingString:object[#"LastName"]];
cell.profileName.text = names;
cell.contentLabel.text = object[#"Request"];
cell.firstName = object[#"FirstName"];
cell.lastName = object[#"LastName"];
cell.iostoken = object[#"DeviceID"];
cell.request = names;
cell.prayerObject = object;
PFFile *thumbnail = object[#"ProfilePic"];
cell.profilePic.image = [UIImage imageNamed:#"AppIcon60x60#2x.png"];
/*[cell.commentButton addTarget:self action:#selector(didTapCommentButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[cell.commentButton setTitle:#"Share" forState:UIControlStateNormal];
[cell.commentButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[cell.commentButton setTitleColor:[UIColor greenColor] forState:UIControlStateHighlighted];*/
[thumbnail getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
UIImage *thumbnailImage = [UIImage imageWithData:imageData];
UIImageView *thumbnailImageView = [[UIImageView alloc] initWithImage:thumbnailImage];
cell.profilePic.image = thumbnailImage;
}];
NSString *dates = object[#"dateMade"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM_dd_yyyy"];
NSDate *datefromstring = [formatter dateFromString:dates];
NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:#"MMM dd, yyyy"];
cell.dateLabel.text = [formatter2 stringFromDate:datefromstring];
UIFont *cellFont = [UIFont fontWithName:#"Verdana-Bold" size:15];
UIFont *cellFont2 = [UIFont fontWithName:#"Verdana-Bold" size:12];
}
else {
// Configure the cell to show todo item with a priority at the bottom
cell.profileName.text = object[#"Title"];
cell.contentLabel.text = object[#"Request"];
cell.firstName = object[#"FirstName"];
cell.lastName = object[#"LastName"];
cell.iostoken = object[#"DeviceID"];
cell.request = object[#"Title"];
cell.prayerObject = object;
PFFile *thumbnail = object[#"ProfilePic"];
cell.profilePic.image = [UIImage imageNamed:#"AppIcon60x60#2x.png"];
[thumbnail getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
UIImage *thumbnailImage = [UIImage imageWithData:imageData];
UIImageView *thumbnailImageView = [[UIImageView alloc] initWithImage:thumbnailImage];
cell.profilePic.image = thumbnailImage;
}];
NSString *dates = object[#"dateMade"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM_dd_yyyy"];
NSDate *datefromstring = [formatter dateFromString:dates];
NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:#"MMM dd, yyyy"];
cell.dateLabel.text = [formatter2 stringFromDate:datefromstring];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
PFObject *entry = [self.objects objectAtIndex:indexPath.row];
NSString *commentString = entry[#"Request"];
NSString *nameString = #"";
NSLog(#"%#", commentString);
return [Cell heightForCellWithContentString:(NSString *)commentString] +25 ;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad )
{
if (_webViewController2 == nil) {
self.webViewController2 = [[[WebViewController2 alloc] initWithNibName:#"WebViewController2" bundle:[NSBundle mainBundle]] autorelease];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
_webViewController2.entry = entry;
[self.navigationController pushViewController:_webViewController2 animated:YES];
[self.objects objectAtIndex:indexPath.row];
}
else {
PFObject *entry = [self.objects objectAtIndex:indexPath.row];
if (_webViewController == nil) {
self.webViewController = [[[WebViewController alloc] initWithNibName:#"WebViewController" bundle:[NSBundle mainBundle]] autorelease];
}
_webViewController.finalObject = entry;
[self.navigationController pushViewController:_webViewController animated:YES];
}
#endif
}
As I understand, that should load up 20 items at a time, and when you scroll to the end of those, load up the next 20. However, once I have 20 items, the app crashes, and I get this message:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 20 beyond bounds [0 .. 19]'
After putting an exception breakpoint in, the line causing the error is in the heightForRow method
PFObject *entry = [self.objects objectAtIndex:indexPath.row];
What's going on?

TableView Disappears on segmented control

So I have a uitableviewcontroller with a segmented control in the navigation bar. I can get the tableview to reload the first time at index 0 and the second time at index 1. When I try to go back to the first index and the entire tableview disappears.
The problem only occurs when the segmented control index is 1 and the tableview section 2 is empty. If there are objects in that area, It works fine and I can switch back and forth between the two tableviews.
I also realized that when I pulled down the refresh control, it says that I have an empty array in the debug area. I put breakpoints within the refresh control method to see what the problem with that was and the problem is before the refresh control method gets fired off...how??
This is not a duplicate question and would appreciate any help I can seeing as this the place to go for all answers. Thanks!
Also, the entire uitableviewcontroller class is extremely long so if you would really like to see it please ask
NewsFeed.m File https://dl.dropboxusercontent.com/u/10826637/NewsTableViewController.m
VERY LONG
#import "NewsTableViewController.h"
#import "OtherNewsViewController.h"
#import "MSCellAccessory.h"
#interface NewsTableViewController ()
{
PFUser *_loggedInUser;
NSIndexPath *_newIndexPath;
PFObject *_clubInvite;
PFObject *_clubRequest;
UIRefreshControl *_refreshControl;
PFUser *_clubInviteUser;
PFUser *_clubRequestUser;
int _rowOneCount;
int _rowTwoCount;
NSMutableArray *_myFollowingArray;
}
#end
#implementation NewsTableViewController
- (void)viewDidLoad {
UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"" style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.backBarButtonItem = backButtonItem;
[self.segmentControl addTarget:self action:#selector(changedValue) forControlEvents:UIControlEventValueChanged];
_refreshControl = [[UIRefreshControl alloc] init];
[_refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
[self.tableView addSubview:_refreshControl];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:YES];
_loggedInUser = [PFUser currentUser];
_myFollowingArray = [NSMutableArray arrayWithArray:_loggedInUser[#"Following"]];
if (![_myFollowingArray containsObject:_loggedInUser.username]) {
[_myFollowingArray addObject:_loggedInUser.username];
}
if (self.segmentControl.selectedSegmentIndex == 0) {
PFQuery *userQuery = [PFUser query];
[userQuery whereKey:#"username" containedIn:_myFollowingArray];
PFQuery *newsQuery = [PFQuery queryWithClassName:#"News"];
[newsQuery whereKey:#"Notified" matchesQuery:userQuery];
[newsQuery setLimit:50];
[newsQuery orderByDescending:#"createdAt"];
[newsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
self.followingNews = objects;
[self.tableView reloadData];
}];
} else if (self.segmentControl.selectedSegmentIndex == 1) {
PFQuery *inviteQuery = [PFQuery queryWithClassName:#"ClubInvites"];
[inviteQuery whereKey:#"Invited" equalTo:_loggedInUser];
[inviteQuery whereKey:#"Accepted" equalTo:[NSNumber numberWithBool:NO]];
[inviteQuery countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
_rowOneCount = number;
[self.tableView reloadData];
}];
PFQuery *requestsQuery = [PFQuery queryWithClassName:#"ClubRequests"];
[requestsQuery whereKey:#"Owner" equalTo:_loggedInUser];
[requestsQuery whereKey:#"Accepted" equalTo:[NSNumber numberWithBool:NO]];
[requestsQuery countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
_rowTwoCount = number;
[self.tableView reloadData];
}];
PFQuery *myNewsQuery = [PFQuery queryWithClassName:#"News"];
[myNewsQuery setLimit:50];
[myNewsQuery orderByDescending:#"createdAt"];
[myNewsQuery whereKey:#"Notified" equalTo:_loggedInUser];
[myNewsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
self.myNews = objects;
[self.tableView reloadData];
}];
} else if (self.segmentControl.selectedSegmentIndex == 2) {
[self.tableView reloadData];
}
}
- (void)changedValue {
if (self.segmentControl.selectedSegmentIndex == 0) {
PFQuery *userQuery = [PFUser query];
[userQuery whereKey:#"username" containedIn:_myFollowingArray];
PFQuery *newsQuery = [PFQuery queryWithClassName:#"News"];
[newsQuery setLimit:50];
[newsQuery orderByDescending:#"createdAt"];
[newsQuery whereKey:#"Notified" matchesQuery:userQuery];
[newsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
self.followingNews = objects;
[self.tableView reloadData];
}];
} else if (self.segmentControl.selectedSegmentIndex == 1) {
PFQuery *inviteQuery = [PFQuery queryWithClassName:#"ClubInvites"];
[inviteQuery whereKey:#"Invited" equalTo:_loggedInUser];
[inviteQuery whereKey:#"Accepted" equalTo:[NSNumber numberWithBool:NO]];
[inviteQuery countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
_rowOneCount = number;
[self.tableView reloadData];
}];
PFQuery *requestsQuery = [PFQuery queryWithClassName:#"ClubRequests"];
[requestsQuery whereKey:#"Owner" equalTo:_loggedInUser];
[requestsQuery whereKey:#"Accepted" equalTo:[NSNumber numberWithBool:NO]];
[requestsQuery countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
_rowTwoCount = number;
[self.tableView reloadData];
}];
PFQuery *myNewsQuery = [PFQuery queryWithClassName:#"News"];
[myNewsQuery setLimit:50];
[myNewsQuery orderByDescending:#"createdAt"];
[myNewsQuery whereKey:#"Notified" equalTo:_loggedInUser];
[myNewsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
self.myNews = objects;
[self.tableView reloadData];
}];
} else if (self.segmentControl.selectedSegmentIndex == 2) {
[self.tableView reloadData];
}
}
-(void)refresh:(UIRefreshControl *)refreshControl {
if (self.segmentControl.selectedSegmentIndex == 0) {
PFQuery *userQuery = [PFUser query];
[userQuery whereKey:#"username" containedIn:_loggedInUser[#"Following"]];
PFQuery *newsQuery = [PFQuery queryWithClassName:#"News"];
[newsQuery whereKey:#"Notified" matchesQuery:userQuery];
[newsQuery setLimit:50];
[newsQuery orderByDescending:#"createdAt"];
[newsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
self.followingNews = objects;
[self.tableView reloadData];
}];
[_refreshControl endRefreshing];
} else {
PFQuery *inviteQuery = [PFQuery queryWithClassName:#"ClubInvites"];
[inviteQuery whereKey:#"Invited" equalTo:_loggedInUser];
[inviteQuery whereKey:#"Accepted" equalTo:[NSNumber numberWithBool:NO]];
[inviteQuery countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
_rowOneCount = number;
[self.tableView reloadData];
}];
PFQuery *requestsQuery = [PFQuery queryWithClassName:#"ClubRequests"];
[requestsQuery whereKey:#"Owner" equalTo:_loggedInUser];
[requestsQuery whereKey:#"Accepted" equalTo:[NSNumber numberWithBool:NO]];
[requestsQuery countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
_rowTwoCount = number;
[self.tableView reloadData];
}];
PFQuery *myNewsQuery = [PFQuery queryWithClassName:#"News"];
[myNewsQuery setLimit:50];
[myNewsQuery orderByDescending:#"createdAt"];
[myNewsQuery whereKey:#"Notified" equalTo:_loggedInUser];
[myNewsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
self.myNews = objects;
[_refreshControl endRefreshing];
[self.tableView reloadData];
}];
}
}
- (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.
if (self.segmentControl.selectedSegmentIndex == 0) {
return 1;
} else {
return 3;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (self.segmentControl.selectedSegmentIndex == 0) {
return self.followingNews.count;
} else {
if (section == 2) {
return self.myNews.count;
} else {
return 1;
}
}
}
//Long tableview configuration method for segumented controller
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = #"Cell";
NSString *cellIdentifier2 = #"Cell2";
UITableViewCell *cell = nil;
if (self.segmentControl.selectedSegmentIndex == 0) {
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier2];
self.cellImageView = (UIImageView *)[cell.contentView viewWithTag:1];
self.cellImageView.layer.cornerRadius = 6.0f;
self.cellImageView.clipsToBounds = YES;
//Create the cell label going into the cell
self.cellLabel = (UILabel *)[cell.contentView viewWithTag:3];
[cell.contentView addSubview:self.cellLabel];
[cell.contentView addSubview:self.cellImageView];
PFObject *eachNews = [self.followingNews objectAtIndex:indexPath.row];
PFUser *notifier = [eachNews objectForKey:#"Notifier"];
PFUser *notified = [eachNews objectForKey:#"Notified"];
[notifier fetchIfNeeded];
[notified fetchIfNeeded];
NSString *notifierString = [[NSString alloc] init];
NSString *notifiedString = [[NSString alloc] init];
NSString *grammer = [[NSString alloc] init];
NSDate *timeStamp = eachNews.createdAt;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM d, yyyy h:mm a"];
NSString *timeString = [dateFormatter stringFromDate:timeStamp];
if ([notifier.username isEqualToString:_loggedInUser.username]) {
notifierString = #"You";
grammer = #"are";
} else {
notifierString = notifier[#"username"];
grammer = #"is";
}
if ([notified.username isEqualToString: _loggedInUser.username]) {
notifiedString = #"you";
} else {
notifiedString = notified.username;
}
if (notifier[#"profileImage"] == nil) {
UIImage *hermet = [UIImage imageNamed:#"ohyeah.jpg"];
[self.cellImageView setImage:hermet];
} else {
PFFile *imageFile = notifier[#"profileImage"];
[self.cellImageView setImage:[UIImage imageWithData:[imageFile getData]]];
}
NSMutableString *newsText = [[NSMutableString alloc] init];
if ([eachNews[#"Type"] isEqualToString:#"Follow"]) {
[newsText appendString:[NSString stringWithFormat:#"%# %# %#. ", notifierString, eachNews[#"Messages"], notifiedString]];
} else if ([eachNews[#"Type"] isEqualToString:#"New Founder"]) {
[newsText appendString:[NSString stringWithFormat:#"%# %# %#. ", notifierString, grammer, eachNews[#"Messages"]]];
}
[newsText appendString:timeString];
NSArray *appendedString = [newsText componentsSeparatedByString:#" "];
NSRange dateRange = [newsText rangeOfString:appendedString[1]];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:newsText];
[attrString beginEditing];
[attrString addAttribute: NSForegroundColorAttributeName
value:[UIColor lightGrayColor]
range:dateRange];
[attrString endEditing];
self.cellLabel.attributedText = attrString;
self.cellLabel.numberOfLines = 0;
self.cellLabel.font = [UIFont systemFontOfSize:14];
CGSize constrainedSize = CGSizeMake(self.cellLabel.frame.size.width , CGFLOAT_MAX);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:14.0], NSFontAttributeName,
nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:self.cellLabel.text attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (requiredHeight.size.height > self.cellLabel.frame.size.height) {
requiredHeight = CGRectMake(0,0, self.cellLabel.frame.size.width, requiredHeight.size.height);
}
CGRect newFrame = self.cellLabel.frame;
newFrame.size.height = requiredHeight.size.height + 20;
self.cellLabel.frame = newFrame;
}
if (self.segmentControl.selectedSegmentIndex == 1) {
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
//Invites section
cell.imageView.image = nil;
cell.detailTextLabel.text = nil;
if (indexPath.section == 0) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
if (_rowOneCount == 0) {
[cell.textLabel setTextColor:[UIColor lightGrayColor]];
cell.accessoryView = nil;
} else {
[cell.textLabel setTextColor:[UIColor blackColor]];
cell.accessoryView = [MSCellAccessory accessoryWithType:FLAT_DISCLOSURE_INDICATOR color:[UIColor orangeColor]];
}
cell.textLabel.text = [NSString stringWithFormat:#"Invites (%i)", _rowOneCount];
cell.textLabel.font = [UIFont systemFontOfSize:18];
//Requested section
} else if (indexPath.section == 1){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
if (_rowTwoCount == 0) {
[cell.textLabel setTextColor:[UIColor lightGrayColor]];
cell.accessoryView = nil;
} else {
[cell.textLabel setTextColor:[UIColor blackColor]];
cell.accessoryView = [MSCellAccessory accessoryWithType:FLAT_DISCLOSURE_INDICATOR color:[UIColor orangeColor]];
}
cell.textLabel.font = [UIFont systemFontOfSize:18];
cell.textLabel.text = [NSString stringWithFormat:#"Requests (%i)", _rowTwoCount];
//Requested count is greater than 0
} else if (indexPath.section == 2) {
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
//Create the ImageViwew that is going into the cell
self.cellImageView = (UIImageView *)[cell.contentView viewWithTag:1];
self.cellImageView.layer.cornerRadius = 6.0f;
self.cellImageView.clipsToBounds = YES;
//Create the cell label going into the cell
self.cellLabel = (UILabel *)[cell.contentView viewWithTag:3];
[cell.contentView addSubview:self.cellLabel];
[cell.contentView addSubview:self.cellImageView];
if (self.myNews.count == 0) {
self.cellLabel.text = #"";
} else {
PFObject *myNewsObject = [self.myNews objectAtIndex:indexPath.row];
PFUser *meUser = [myNewsObject objectForKey:#"Notifier"];
[meUser fetchIfNeeded];
NSDate *timeStamp = myNewsObject.createdAt;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM d, yyyy h:mm a"];
NSString *timeString = [dateFormatter stringFromDate:timeStamp];
if (meUser[#"profileImage"] == nil) {
UIImage *hermet = [UIImage imageNamed:#"ohyeah.jpg"];
[self.cellImageView setImage:hermet];
} else {
PFFile *imageFile = meUser[#"profileImage"];
[self.cellImageView setImage:[UIImage imageWithData:[imageFile getData]]];
}
self.cellImageView.contentMode = UIViewContentModeScaleAspectFit;
NSMutableString *newsText = [[NSMutableString alloc] init];
if ([myNewsObject[#"Type"] isEqualToString:#"Follow"]) {
[newsText appendString:[NSString stringWithFormat:#"%# %# you. ", meUser.username, myNewsObject[#"Messages"]]];
} else if ([myNewsObject[#"Type"] isEqualToString:#"New Founder"]){
[newsText appendString:[NSString stringWithFormat:#"You are %#. ", myNewsObject[#"Messages"]] ];
}
[newsText appendString:timeString];
NSArray *appendedString = [newsText componentsSeparatedByString:#" "];
NSRange dateRange = [newsText rangeOfString:appendedString[1]];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:newsText];
[attrString beginEditing];
[attrString addAttribute: NSForegroundColorAttributeName
value:[UIColor lightGrayColor]
range:dateRange];
[attrString endEditing];
self.cellLabel.attributedText = attrString;
self.cellLabel.numberOfLines = 0;
self.cellLabel.font = [UIFont systemFontOfSize:14];
CGSize constrainedSize = CGSizeMake(self.cellLabel.frame.size.width , CGFLOAT_MAX);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:14.0], NSFontAttributeName,
nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:self.cellLabel.text attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (requiredHeight.size.height > self.cellLabel.frame.size.height) {
requiredHeight = CGRectMake(0,0, self.cellLabel.frame.size.width, requiredHeight.size.height);
}
CGRect newFrame = self.cellLabel.frame;
newFrame.size.height = requiredHeight.size.height + 20;
self.cellLabel.frame = newFrame;
}
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
if (self.segmentControl.selectedSegmentIndex == 2) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
cell.accessoryView = nil;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.imageView.layer.cornerRadius = 6.0f;
cell.imageView.clipsToBounds = YES;
cell.textLabel.text = #"Some Events";
}
return cell;
}
- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (self.segmentControl.selectedSegmentIndex == 1) {
NSArray *headerTitles = [[NSArray alloc] initWithObjects:#"Invites", #"Requests", #"Notifications", nil];
NSString *title = [headerTitles objectAtIndex:section];
return title;
} else if (self.segmentControl.selectedSegmentIndex == 0) {
return #"Following News";
} else {
return #"Events";
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.segmentControl.selectedSegmentIndex == 1) {
if (indexPath.section == 0) {
if (_rowOneCount == 0) {
return;
} else {
[self performSegueWithIdentifier:#"showInvites" sender:self.tableView];
}
} else if (indexPath.section == 1) {
if (_rowTwoCount == 0) {
return;
} else {
[self performSegueWithIdentifier:#"showRequests" sender:self.tableView];
}
} else if (indexPath.section == 2) {
return;
}
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.segmentControl.selectedSegmentIndex == 0) {
if (self.followingNews.count == 0) {
return 50;
} else {
PFObject *eachNews = [self.myNews objectAtIndex:indexPath.row];
PFUser *notifier = [eachNews objectForKey:#"Notifier"];
PFUser *notified = [eachNews objectForKey:#"Notified"];
[notifier fetchIfNeeded];
[notified fetchIfNeeded];
NSString *notifierString = [[NSString alloc] init];
NSString *notifiedString = [[NSString alloc] init];
if ([notifier.username isEqualToString:_loggedInUser.username]) {
notifierString = #"You";
} else {
notifierString = notifier.username;
}
if ([notified.username isEqualToString: _loggedInUser.username]) {
notifiedString = #"you";
} else {
notifiedString = notified.username;
}
NSString *fullString = [[NSString alloc] init];
if ([eachNews[#"Type"] isEqualToString:#"Follow"]) {
fullString = [NSString stringWithFormat:#"%# %# %#.", notifierString, eachNews[#"Messages"], notifiedString];
} else if ([eachNews[#"Type"] isEqualToString:#"New Founder"]) {
fullString = [NSString stringWithFormat:#"%# %#.", notifierString, eachNews[#"Messages"]];
}
CGSize constrainedSize = CGSizeMake(200, CGFLOAT_MAX);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:14.0], NSFontAttributeName,
nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:fullString attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (requiredHeight.size.height > 45) {
requiredHeight = CGRectMake(0,0, 200, requiredHeight.size.height);
}
return requiredHeight.size.height + 50;
}
} else {
if (indexPath.section == 2) {
if (self.myNews.count == 0) {
return 50;
} else {
PFObject *myNewsObject = [self.myNews objectAtIndex:indexPath.row];
PFUser *meUser = [myNewsObject objectForKey:#"Notifier"];
[meUser fetchIfNeeded];
NSString *fullString = [[NSString alloc] init];
if ([myNewsObject[#"Type"] isEqualToString:#"Follow"]) {
fullString = [NSString stringWithFormat:#"%# %# you.", meUser.username, myNewsObject[#"Messages"]];
} else if ([myNewsObject[#"Type"] isEqualToString:#"New Founder"]) {
fullString = [NSString stringWithFormat:#"You are %#.", myNewsObject[#"Messages"]];
}
CGSize constrainedSize = CGSizeMake(200, CGFLOAT_MAX);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:14.0], NSFontAttributeName,
nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:fullString attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (requiredHeight.size.height > 45) {
requiredHeight = CGRectMake(0,0, 200, requiredHeight.size.height);
}
return requiredHeight.size.height + 50;
}
} else {
return 50;
}
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
OtherNewsViewController *otherVC = segue.destinationViewController;
if ([segue.identifier isEqualToString:#"showInvites"]) {
otherVC.segueIdentifier = #"Invites";
otherVC.navigationItem.title = #"Invites";
} else if ([segue.identifier isEqualToString:#"showRequests"]) {
otherVC.segueIdentifier = #"Requests";
otherVC.navigationItem.title = #"Requests";
}
}
#end
Nevermind I found the answer/where the problem was! in heightForRowAtIndexPath method, I was passing in the wrong array when grabbing the objects
if (self.followingNews.count == 0) {
return 50;
} else {
PFObject *eachNews = [self.myNews objectAtIndex:indexPath.row];
This the array in the first part of the IF statement was not used in the initialization of PFObject. I was using self.myNews instead. I guess figuring out problems really just takes time!

Did Selected Row App Crash

Hello everyone I was following a tutorial where I explain how to expand the cells did with selected row
I've implemented all the array and returns the data correctly but when I go to select the cell to expand my application crashes giving me back this error
[ PFObject sizeWithFont : constrainedToSize : lineBreakMode :]: unrecognized selector sent to instance
with the breakpoint I find the point but I do not understand what's wrong ...
The point where the app crashes is
CGSize AltezzaLabel = [ [ ArrayforPost objectAtIndex : index ] sizew sizeWithFont : [ UIFont fontWithName : # " Helvetica " size : 14.0f ] constrainedToSize : MAX lineBreakMode : NSLineBreakByCharWrapping ] ;
Below I provide the implementation for better understanding
#import "FFTimeline.h"
#import "FFCustomCellTimelineSocial.h"
#interface FFTimeline ()
#end
#implementation FFTimeline
#synthesize ArrayforPost, NuovoArray;
#synthesize IsFlashPost;
- (void)viewDidLoad
{
[super viewDidLoad];
self.FFTableView.delegate = self;
self.FFTableView.dataSource = self;
CellaSelezionata = -1;
}
-(void)viewDidAppear:(BOOL)animated {
[self QueryForPost];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [ArrayforPost count];
}
-(void)QueryForPost {
PFQuery *QueryForFriend=[PFQuery queryWithClassName:FF_AMICIZIE_CLASS];
[QueryForFriend whereKey:FF_AMICIZIE_A_USER equalTo:[PFUser currentUser]];
[QueryForFriend whereKey:FF_AMICIZIE_STATO equalTo:#"Confermato"];
[QueryForFriend includeKey:FF_AMICIZIE_DA_USER];
PFQuery *QueryYES = [PFQuery queryWithClassName:FF_POST_CLASS];
[QueryYES whereKey:FF_POST_FLASH_POST_BOOLEANVALUE equalTo:[NSNumber numberWithBool:YES]];
[QueryYES whereKey:FF_POST_SCELTI equalTo:[PFUser currentUser]];
PFQuery *normalPostByFriends = [PFQuery queryWithClassName: FF_POST_CLASS];
[normalPostByFriends whereKey: FF_POST_FLASH_POST_BOOLEANVALUE equalTo: [NSNumber numberWithBool: NO]];
[normalPostByFriends whereKey: FF_POST_UTENTE matchesKey:FF_AMICIZIE_DA_USER inQuery:QueryForFriend];
PFQuery *normalPostByUser = [PFQuery queryWithClassName:FF_POST_CLASS];
[normalPostByUser whereKey:FF_POST_FLASH_POST_BOOLEANVALUE equalTo: [NSNumber numberWithBool: NO]];
[normalPostByUser whereKey:FF_POST_UTENTE equalTo: [PFUser currentUser]];
PFQuery *query = [PFQuery orQueryWithSubqueries:#[QueryYES,normalPostByFriends,normalPostByUser]];
[query includeKey:FF_POST_UTENTE];
[query orderByDescending:FF_CREATEDAT];
[query findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
if (!error) {
NSLog(#"%#", results);
ArrayforPost = [[NSMutableArray alloc] init];
for (PFObject *object in results) {
[ArrayforPost addObject:object];
}
[self.FFTableView reloadData];
}
}];
}
-(CGFloat)valoreAltezzaCella:(NSInteger)index {
CGSize MAX = CGSizeMake(230, 10000);
CGSize AltezzaLabel = [[ArrayforPost objectAtIndex:index] sizeWithFont:[UIFont fontWithName:#"Helvetica" size:14.0f] constrainedToSize:MAX lineBreakMode:NSLineBreakByWordWrapping];
return AltezzaLabel.height;
}
- (FFCustomCellTimelineSocial *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
FFCustomCellTimelineSocial *cell = (FFCustomCellTimelineSocial * )[self.FFTableView dequeueReusableCellWithIdentifier:#"CellPost"];
if (!cell) {
cell = [[FFCustomCellTimelineSocial alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CellPost"];
}
if (CellaSelezionata == indexPath.row) {
CGFloat AltezzaLabel = [self valoreAltezzaCella: indexPath.row];
cell.FFTestoUtenteLabel.frame = CGRectMake(cell.FFTestoUtenteLabel.frame.origin.x, cell.FFTestoUtenteLabel.frame.origin.y, cell.FFTestoUtenteLabel.frame.size.width, AltezzaLabel);
} else {
cell.FFTestoUtenteLabel.frame = CGRectMake(cell.FFTestoUtenteLabel.frame.origin.x, cell.FFTestoUtenteLabel.frame.origin.y, cell.FFTestoUtenteLabel.frame.size.width, 65);
}
PFObject *ObjectPost = [ArrayforPost objectAtIndex:indexPath.row];
cell.FFTestoUtenteLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0f];
NSString *text = [ObjectPost objectForKey:#"Testo"];
cell.FFTestoUtenteLabel.text = text;
[cell.FFTestoUtenteLabel setLineBreakMode:NSLineBreakByWordWrapping];
cell.backgroundCell.layer.masksToBounds = YES;
cell.backgroundCell.layer.cornerRadius = 5.0f;
cell.backgroundFotoProfilo.layer.masksToBounds = YES;
cell.backgroundFotoProfilo.layer.cornerRadius = 35.0f;
cell.FFImmagineUtente.layer.masksToBounds = YES;
cell.FFImmagineUtente.layer.cornerRadius = 30.0f;
cell.FFImmagineUtente.contentMode = UIViewContentModeScaleAspectFill;
PFObject *rowObject = [ArrayforPost objectAtIndex:indexPath.row];
if([[rowObject objectForKey:FF_POST_FLASH_POST_BOOLEANVALUE ] boolValue]) {
cell.FlashPostImg.image = [UIImage imageNamed:#"FFNotificaFlash"];
}
else {
cell.FlashPostImg.image = [UIImage imageNamed:#" "];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
if (CellaSelezionata == indexPath.row)
{
return [self valoreAltezzaCella:indexPath.row] + 10 * 2;
}
else {
return 65 + 10 * 2;
}
}
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self valoreAltezzaCella:indexPath.row] > 65) {
return indexPath;
} else {
return nil;
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (CellaSelezionata == indexPath.row) {
CellaSelezionata = -1;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
return;
}
if (CellaSelezionata >= 0) {
NSIndexPath *previousPath = [NSIndexPath indexPathForRow:CellaSelezionata inSection:0];
CellaSelezionata = indexPath.row;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:previousPath] withRowAnimation:UITableViewRowAnimationFade];
}
CellaSelezionata = indexPath.row;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
In your valoreAltezzaCella: method, [ArrayforPost objectAtIndex:index] is a PFObject and not a NSString, so you cannot apply sizeWithFont to it. You probably want something similar to:
PFObject *objectPost = [ArrayforPost objectAtIndex:indexPath.row];
NSString *text = [objectPost objectForKey:#"Testo"];
CGSize altezzaLabel = [text sizeWithFont:[UIFont fontWithName:#"Helvetica" size:14.0f] constrainedToSize:MAX lineBreakMode:NSLineBreakByWordWrapping];

Resources