releasing thread1 exc_bad_access - ios

I am new at IOS programing and I have program that works fine, but I found out that it has memory leek, so I start releasing object.
When I now start the program it give me an error:
#autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
and :
Thread 1: EXC_BAD_ACCESS (code = 1, address = 0x3f800010)
I tried to debug it and I found out that program crashed at creating tableView.
It create whole first section, but in the second row in second section it crashed in the returning line.
here is my code of creating table:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView setBackgroundView:nil];
tableView.backgroundColor = [UIColor clearColor];
// Configure the cell...
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
if (!indexPath.row)
{
static NSString *CellIdentifier = #"TitleCell";
UILabel *title;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = nil;
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"TitleCell" owner:self options:nil];
titleCell.layer.masksToBounds = YES;
titleCell.layer.cornerRadius =0.0;
cell = titleCell;
self.titleCell = nil;
}
title =(UILabel *)[cell viewWithTag:1];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSString *orderString=[[[NSString alloc] init] autorelease];
title.text = [[titles objectAtIndex:indexPath.section] objectAtIndex:2];
cell.accessoryView = nil;
if (!isPad()) {
[cell.contentView setBackgroundColor:[UIColor colorWithRed:0.0 green:0.18 blue:0.24 alpha:1]];
}
return cell;
}
else
{
// all other rows
static NSString *CellIdentifier = #"DataCell";
UILabel *title;
UILabel *update;
UILabel *download;
UILabel *updateText;
UILabel *downloadText;
UIImageView *favoriteIcon;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = nil;
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"DataCell" owner:self options:nil];
cell = dataCell;
self.dataCell = nil;
}
cell.layer.cornerRadius =0;
title =(UILabel *)[cell viewWithTag:1];
download = (UILabel *)[cell viewWithTag:3];
update = (UILabel *)[cell viewWithTag:2];
favoriteIcon = (UIImageView *)[cell viewWithTag:4];
updateText = (UILabel *)[cell viewWithTag:5];
downloadText = (UILabel *)[cell viewWithTag:6];
updateText.text = NSLocalizedString(#"updated", nil);
downloadText.text = NSLocalizedString(#"downloaded", nil);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM. d. YYYY"];
starIcone = favoriteIcon;
int indicator = 0;
for (int i=0; i<[allData count]; i++) {
if ([[[allData objectAtIndex:i] objectAtIndex:1] isEqualToNumber:[[titles objectAtIndex:indexPath.section] objectAtIndex:0]] ) {
indicator++;
}
if (indicator == indexPath.row) {
title.text = [[allData objectAtIndex:i] objectAtIndex:2];
download.text = [dateFormat stringFromDate:[self db_get_date:[[[allData objectAtIndex:i] objectAtIndex:0]intValue]]];
update.text = [dateFormat stringFromDate:[[allData objectAtIndex:i] objectAtIndex:3]];
break;
}
}
[dateFormat release];
[favoriteIcon setAccessibilityHint:title.text];
if ([favorits count]==0) {
favoriteIcon.image = [[UIImage alloc]
initWithContentsOfFile:
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:
#"blankstar.png"]];
}
for (int i=0; i<[favorits count]; i++) {
if ([title.text isEqualToString:[[favorits objectAtIndex:i] objectAtIndex:2]]) {
favoriteIcon.image = [[UIImage alloc]
initWithContentsOfFile:
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:
#"star.png"]];
break;
}
else {
favoriteIcon.image = [[UIImage alloc]
initWithContentsOfFile:
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:
#"blankstar.png"]];
}
}
UITapGestureRecognizer *recognizer = [[[UITapGestureRecognizer alloc]
initWithTarget:self action:#selector(AddIcone:)]autorelease
];
[favoriteIcon setUserInteractionEnabled:YES];
[favoriteIcon addGestureRecognizer:recognizer];
cell.backgroundColor = [UIColor clearColor];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
return cell;
}
}
return nil;
I also tried just putting :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TitleCell";
UILabel *title;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = nil;
if (cell == nil) {
self.titleCell = [[[NSBundle mainBundle] loadNibNamed:#"TitleCell" owner:self options:nil]objectAtIndex:0];
titleCell.layer.masksToBounds = YES;
titleCell.layer.cornerRadius =0.0;
cell = titleCell;
self.titleCell = nil;
}
return cell;
and it crash as before.
pleas help me out and thank for your help.

[[NSBundle mainBundle] loadNibName: owner: options:] returns an array.
Replace this line with:
self.titleCell = [[[NSBundle mainBundle] loadNibNamed:#"TitleCell" owner:self options:nil] objectAtIndex:0];

Related

Index out of bounds when passed through segue

I have 3 custom table cells in my UITableView. The first two cells have set positions followed by a random number of cells.
For my row count I use :
return [stepLabel count] +2;
And for my tablecells I use :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *stepsCellIdentifier = #"StepsViewCell";
static NSString *descIdentfier = #"descViewCell";
static NSString *videoCellIdentfier = #"videoViewCell";
if( indexPath.row == 0 ) {
UITableViewCell *cell = nil;
cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:videoCellIdentfier];
if( !cell ) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"videoViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.textLabel.text = [descLabel objectAtIndex:indexPath.row];
return cell;
}
else if( indexPath.row == 1 ) {
stepDescCell *cell = nil;
cell = (stepDescCell *)[tableView dequeueReusableCellWithIdentifier:descIdentfier];
if( !cell ) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"descViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.descTextLabel.text = [descLabel objectAtIndex:indexPath.row - 1];
return cell;
}
else {
StepViewCell *cell = nil;
cell = (StepViewCell *)[tableView dequeueReusableCellWithIdentifier:stepsCellIdentifier];
if( !cell ) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"StepsViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.stepTextLbl.text = [stepLabel objectAtIndex:(indexPath.row - 2)];
NSString *imageThumb = [thumbImg objectAtIndex:(indexPath.row - 2)];
[cell.thumbImage setImage:[UIImage imageNamed: imageThumb] forState:UIControlStateNormal];
return cell;
}
}
All this works perfectly, however when I try to send a string from the table across a segue to another UIViewController I get the following error:
index (-2 (or possibly larger)) beyond bounds (3)'
The prepare for segue method:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"imageBigShow"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
imageBigViewController *destViewController = segue.destinationViewController;
NSString *largeImgString = [largeImg objectAtIndex:(indexPath.row - 2)];
destViewController.imageBigString = largeImgString;
}
}
What am I doing wrong?
UPDATE
#implementation detailViewController
{
NSArray *thumbImg;
NSArray *stepLabel;
NSArray *descLabel;
NSArray *largeImg;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Find out the path of recipes.plist
NSDictionary *mapping = #{
#"How to wear a Kilt" : #"wearAKilt",
#"How to tie a cravat" : #"wearACravat",
#"How to wear a sporran" : #"wearASporran",
#"How to tie Ghillie Brogues" : #"wearTheShoes",
#"How to wear the accessories" : #"wearAccessories",
#"How to tie a cravat" : #"wearACravat",
#"How to Measure the Neck" : #"htmNeck",
#"How to Measure the chest" : #"htmChest",
#"How to Measure the waist" : #"htmWaist",
};
NSString *name = [mapping objectForKey:self.title];
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:#"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
thumbImg = [dict objectForKey:#"thumbImg"];
stepLabel = [dict objectForKey:#"stepLabel"];
descLabel = [dict objectForKey:#"descLabel"];
largeImg = [dict objectForKey:#"largeImg"];
}
You have the following line:
NSString *largeImgString = [largeImg objectAtIndex:(indexPath.row - 2)];
If the user taps on the 1st or 2nd rows (index paths with row 0 or 1), this code will fail.

First 3 cells are the same but turn correct once I start scrolling?

So Whenever I launch my app it looks like this and the first 3 cells are all the same. But once I start scrolling up and down it fixes and cell 2 and 3 show the correct information.
This is currently how my code looks like:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"MyFeedCell";
SampleTableCell *cell = (SampleTableCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"SampleTableCell" owner:self options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (SampleTableCell *)currentObject;
break;
}
}
}
// Configure the cell.
NSUInteger row = [indexPath row];
NSUInteger count = [_allEntries count];
RSSEntry *entry = [_allEntries objectAtIndex:(count-row-1)];
NSString *imageString = entry.image;
imageString = [imageString stringByReplacingOccurrencesOfString:#"128x67" withString:#"768x432"];
NSLog(#"IMAGE : %#", imageString);
NSURL *imgURL = [[NSURL alloc] initWithString:imageString];
[cell.profilePicture setImageWithURL:imgURL placeholderImage:[UIImage imageNamed:nil]];
NSString *date = [entry.articleDate substringToIndex:12];
cell.datePosted.text = date;
cell.name.text = entry.articleTitle;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
Here's a gif of how it's currently functioning
http://gyazo.com/2011099496257445c008a717beabd8fd
The whole topLevelObjects gambit is no longer necessary, replace your code with this and see if your still getting the problem:
//this above #interface
static NSString *CellIdentifier = #"MyFeedCell";
//Put this in viewDidLoad
[self.table registerClass:[SampleTableCell class] forCellReuseIdentifier:CellIdentifier];
[self.table registerNib:[UINib nibWithNibName:#"SampleTableCell" bundle:nil] forCellReuseIdentifier:CellIdentifier]
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
SampleTableCell *cell = (SampleTableCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell.
NSUInteger row = [indexPath row];
NSUInteger count = [_allEntries count];
RSSEntry *entry = [_allEntries objectAtIndex:(count-row-1)];
NSString *imageString = entry.image;
imageString = [imageString stringByReplacingOccurrencesOfString:#"128x67" withString:#"768x432"];
NSLog(#"IMAGE : %#", imageString);
NSURL *imgURL = [[NSURL alloc] initWithString:imageString];
[cell.profilePicture setImageWithURL:imgURL placeholderImage:[UIImage imageNamed:nil]];
NSString *date = [entry.articleDate substringToIndex:12];
cell.datePosted.text = date;
cell.name.text = entry.articleTitle;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}

setAccessoryType destroys TableViewCell

I use a custom tablecell, labels and images are connected with tags.
If i add
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]
it destroys my tableview. the image destroys and the background-color.
here are the differences:
Does anyone have any idea where the problem could be?
Thanks
EDIT:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
if ([self labelCellNib]) {
[[self labelCellNib] instantiateWithOwner:self options:nil];
} else {
[[NSBundle mainBundle] loadNibNamed:#"LabelCell" owner:self options:nil];
}
cell = self.labelCell;
self.labelCell = nil;
}
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil)
dateFormatter = [[NSDateFormatter alloc] init];
static NSCalendar *calendar;
if(calendar == nil)
calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSString * timeStampString = [sqlTime objectAtIndex:indexPath.row];
NSTimeInterval _interval=[timeStampString doubleValue];
NSDate *createdAt = [NSDate dateWithTimeIntervalSince1970:_interval];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
// Datum in die Tabellen-Zelle einfügen
UILabel *label4 = (UILabel *)[cell viewWithTag:LABEL4];
label4.text = [NSString stringWithFormat:#"%#", [dateFormatter stringFromDate:createdAt]];
// Configure the cell...
UILabel *label1 = (UILabel *)[cell viewWithTag:LABEL1];
label1.text = [NSString stringWithFormat:#"%# %#", [sqlData objectAtIndex:indexPath.row], sonderzeichen];
UILabel *label2 = (UILabel *)[cell viewWithTag:LABEL2];
label2.text = [NSString stringWithFormat:#"Preis pro %#: %# €", sonderzeichen, [sqlPreis objectAtIndex:indexPath.row]];
UILabel *label3 = (UILabel *)[cell viewWithTag:LABEL3];
UIImageView *image = (UIImageView *)[cell viewWithTag:IMAGE_TAG];
if (indexPath.row==[itemsArray count]-1) {
image.image = [UIImage imageNamed:#"default.png"];
label3.text = #"-";
} else if ([itemsArray count]>1) {
int data_old = [[NSString stringWithFormat:#"%#", [sqlData objectAtIndex:indexPath.row]] intValue];
int data_new = [[NSString stringWithFormat:#"%#", [sqlData objectAtIndex:indexPath.row+1]] intValue];
label3.text = [NSString stringWithFormat:#"%i", data_old-data_new];
NSLog(#"%d -- %d", data_old, data_new);
if (data_new>data_old) {
image.image = [UIImage imageNamed:#"pfeil_runter.png"];
} else if (data_new<data_old) {
image.image = [UIImage imageNamed:#"pfeil_hoch.png"];
} else {
image.image = [UIImage imageNamed:#"minus.png"];
}
}
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
cell.contentView.backgroundColor = indexPath.row % 2? [UIColor colorWithRed:228.0/255.0 green:244.0/255.0 blue:199.0/255.0 alpha:1]:[UIColor whiteColor];
return cell;
}
You need to set the background color of the cell, rather than the contentView, but this doesn't work in cellForRowAtIndexPath. It needs to be in willDisplayCell:forRowAtIndexPath:
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = indexPath.row % 2? [UIColor colorWithRed:228.0/255.0 green:244.0/255.0 blue:199.0/255.0 alpha:1]:[UIColor whiteColor];
}
As far as the images getting squashed, that has to do with the size of your subviews, and their constraints. I think you can fix those by giving width constraints to two of your labels (a pair over and under each other), but make their priority <1000, so when the accessory view is added, the width of those labels will get smaller. Also give the image view on the left a fixed width.

Tapping on UIImageView and opening a bigger Image

I have an app that displays, in a tableview, an image and some details. I'm trying to make it so that, when someone touches on the image displayed in my table view, the app opens the same image in a bigger size, with the ability to navigate between them.
This is my current code:
singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(imgTapped:)];
singleTap.numberOfTapsRequired =1;
singleTap.numberOfTouchesRequired = 1;
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [json count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyCell"];
if(cell == nil){
[[NSBundle mainBundle] loadNibNamed:#"AgendaCell" owner:self options:nil];
cell = self.agendaCell;
}
agendaCell.dateCell.text = [[json objectAtIndex:[indexPath row]] objectForKey:#"date"];
agendaCell.enderecoCell.text = [[json objectAtIndex:[indexPath row]] objectForKey:#"endereco"];
agendaCell.tituloCell.text = [[json objectAtIndex:[indexPath row]] objectForKey:#"titulo"];
[agendaCell.imgCell setImageWithURL:[NSURL URLWithString:#"http://sallescds.com.br/wp-content/uploads/2012/12/xepop-300x300.jpg"] placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
[agendaCell.imgCell setUserInteractionEnabled:YES];
[agendaCell.imgCell addGestureRecognizer:singleTap];
return cell;
}
Here is the function when the image is tapped:
-(void)imgTapped:(UIGestureRecognizer *)gestureRecognizer{
NSLog(#"detectado o click no UIImageView BITCH!");
IMGDetailViewController *imgView = [[IMGDetailViewController alloc] initWithNibName:#"IMGDetailViewController" bundle:nil];
[self.navigationController pushViewController:imgView animated:YES];
}
When I try this, the app just crashes.
I don't know how you're setting agendaCell, but usually the line that says:
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"AgendaCell" owner:self options:nil];
cell = self.agendaCell;
}
would be:
if (cell == nil) {
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:#"AgendaCell" owner:self options:nil];
cell = [nibObjects objectAtIndex:0];
}
See How do you load custom UITableViewCells from Xib files?

UIImageView in UITableViewCell repeat

I have a bug.
I want to display a UIImageView on cells at special indexPath.row, but these UIImageView repeat while I scroll.
Exemple: I display my UIImageView on a cell indexPath.row == 0, if I scroll down, I see my UIImageView on the cell at indexPath.row == 8.
Here is my code:
// 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 = [self getCellContentView:CellIdentifier];
}
UILabel *lblTemp1 = (UILabel *)[cell viewWithTag:1];
UIImageView *imgRead = (UIImageView *)[cell viewWithTag:6];
[cell.contentView insertSubview:imgRead aboveSubview:lblTemp1];
contentDictio = [dict objectAtIndex:indexPath.row];
lblTemp1.text = [contentDictio objectForKey:#"title"];
NSArray *paths_id = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath_id = ([paths_id count] > 0) ? [paths_id objectAtIndex:0] : nil;
NSString *path_id = [basePath_id stringByAppendingPathComponent:#"id.plist"];
NSMutableArray *mut_array_id = [[NSArray arrayWithContentsOfFile:path_id] mutableCopy];
NSMutableDictionary *c0 = [[NSMutableDictionary alloc] init];
NSString *idPlistData = [contentDictio objectForKey:#"id"];
for(c0 in mut_array_id) {
if([[c0 objectForKey:#"id"] isEqualToString:idPlistData]) {
[imgRead setImage:[UIImage imageNamed:#"read"]];
}
else {
}
}
}
return cell;
}
- (UITableViewCell *) getCellContentView:(NSString *)cellIdentifier {
CGRect Label1Frame = CGRectMake(kTableCellSmallMargin*2 + 60, kTableCellSmallMargin, 240, 25);
UILabel *lblTemp;
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier] autorelease];
//Initialize Label with tag 1.
lblTemp = [[UILabel alloc] initWithFrame:Label1Frame];
lblTemp.tag = 1;
lblTemp.backgroundColor = [UIColor clearColor];
[lblTemp setFont: [UIFont fontWithName:#"HelveticaNeue-CondensedBold" size:15.0]];
[cell.contentView addSubview:lblTemp];
[lblTemp release];
UIImageView *read=[[UIImageView alloc] initWithFrame:CGRectMake(kTableCellSmallMargin, kTableCellSmallMargin, 60, 60)];
read.backgroundColor=[UIColor clearColor];
read.tag = 6;
[cell.contentView addSubview:read];
[read release];
return cell;
}
Thanks...
The cell is cached, so you have to clear it when you want no image, like this:
BOOL found = NO;
for(c0 in mut_array_id) {
if([[c0 objectForKey:#"id"] isEqualToString:idPlistData]) {
[imgRead setImage:[UIImage imageNamed:#"read"]];
found = YES;
}
else {
}
}
if (!found)
{
[imgRead setImage:nil];
}

Resources