Simple Question UITableView - iphone

Hey everbody. Im getting trouble with a simple thing. But i'm missing some detail. I'm trying to set up the styles of the TableView. I've edited the table on visual, but seems do not take effect what i do.
What im doing wrong?
#implementation ComentariosViewController
#synthesize listaComentarios, tabelaComentarios;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [listaComentarios count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
//cell.font = [UIFont boldSystemFontOfSize:13];
}
NSString *cellValue = [listaComentarios objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
return cell;
}
- (void)viewDidLoad
{
tabelaComentarios = [[UITableView alloc] initWithFrame:CGRectZero];
tabelaComentarios.delegate = self;
tabelaComentarios.dataSource = self;
//bkg.image = [UIImage imageNamed:#"BkgComentarios.png"];
tabelaComentarios.autoresizesSubviews = YES;
//
// Change the properties of the imageView and tableView (these could be set
// in interface builder instead).
//
tabelaComentarios.separatorStyle = UITableViewCellSeparatorStyleNone;
tabelaComentarios.rowHeight = 100;
tabelaComentarios.backgroundColor = [UIColor clearColor];
//imageView.image = [UIImage imageNamed:#"gradientBackground.png"];
//
// Create a header view. Wrap it in a container to allow us to position
// it better.
//
UIView *containerView =
[[[UIView alloc]
initWithFrame:CGRectMake(0, 0, 300, 60)]
autorelease];
UILabel *headerLabel =
[[[UILabel alloc]
initWithFrame:CGRectMake(10, 20, 300, 40)]
autorelease];
headerLabel.text = NSLocalizedString(#"Comentários", #"");
headerLabel.textColor = [UIColor grayColor];
headerLabel.font = [UIFont boldSystemFontOfSize:22];
headerLabel.backgroundColor = [UIColor clearColor];
[containerView addSubview:headerLabel];
self.tabelaComentarios.tableHeaderView = containerView;
self.view = tabelaComentarios;
}
-(void)loadView{
// XML
listaComentarios = [[NSMutableArray alloc] init];
TBXML * tbxml = [[TBXML tbxmlWithURL:[NSURL URLWithString:#"http://localhost/dev/mcomm/produto.xml"]] retain];
TBXMLElement * rootXMLElement = tbxml.rootXMLElement;
TBXMLElement * comentarios = [TBXML childElementNamed:#"comentarios" parentElement:rootXMLElement];
TBXMLElement * comentario = [TBXML childElementNamed:#"comentario" parentElement:comentarios];
while (comentario) {
NSString * descText = [TBXML textForElement:comentario];
NSLog(#"%#", descText);
[listaComentarios addObject:descText];
comentario = [TBXML nextSiblingNamed:#"comentario" searchFromElement:comentario];
}
[tbxml release];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[listaComentarios release];
[tabelaComentarios release];
[super dealloc];
}
#end

If you're using Interface builder to add the table, try commenting out this line:
tabelaComentarios = [[UITableView alloc] initWithFrame:CGRectZero];

Related

IPhone - Images making scrolling and other functionality to crash

Everytime i load images in a tableview and try to scroll the table view i get a crash in my simulator but no errors are showing. Could this be that there is to much memory being used.
Below is the code for 1 out the three views:
#import "ResultViewController.h"
#import "JobAddSiteViewController.h"
#import "SpecificAddViewController.h"
#import "JobAddSiteAppDelegate.h"
#import "JSONKit.h"
#implementation ResultViewController
#synthesize listData;
#synthesize listLocation;
#synthesize listPostDate;
#synthesize listLogo;
#synthesize listDescription;
#synthesize uiTableView;
#synthesize buttonPrev;
#synthesize buttonNext;
NSInteger *countPage = 1;
NSMutableArray *tempArray;
NSMutableArray *tempArray2;
NSMutableArray *tempArray3;
NSMutableArray *tempArray4;
NSMutableArray *tempArray5;
-(IBAction)done{
JobAddSiteViewController *second = [[JobAddSiteViewController alloc]initWithNibName:nil bundle:nil];
[self presentModalViewController:second animated:YES];
[second release];
}
-(void)loadData{
NSString *strURL2 = [NSString stringWithFormat:#"http://www.bestitjobs.co.uk/totaljobs.php", ""];
NSData *nsData2 = [NSData dataWithContentsOfURL:[NSURL URLWithString: strURL2]];
NSString *dataResult = [[NSString alloc] initWithData:nsData2 encoding:NSUTF8StringEncoding];
tempArray = [[NSMutableArray alloc] init];
tempArray2 = [[NSMutableArray alloc] init];
tempArray3 = [[NSMutableArray alloc] init];
tempArray4 = [[NSMutableArray alloc] init];
tempArray5 = [[NSMutableArray alloc] init];
NSString *strURL = [NSString stringWithFormat:#"http://www.bestitjobs.co.uk/appresults3.php?pg=%d", countPage];
NSData *nsData = [NSData dataWithContentsOfURL:[NSURL URLWithString: strURL]];
NSDictionary *listDictionary = [nsData objectFromJSONData];
NSArray* people =[listDictionary objectForKey:#"jobs"];
for (NSDictionary *person in people) {
NSString *str = [NSString stringWithFormat:#"%#", [person valueForKey:#"position"]];
NSString *str2 = [NSString stringWithFormat:#"%#", [person valueForKey:#"subcounty"]];
NSString *str3 = [NSString stringWithFormat:#"%#", [person valueForKey:#"postdate"]];
NSString *str4 = [NSString stringWithFormat:#"%#", [person valueForKey:#"logo"]];
NSString *str5 = [NSString stringWithFormat:#"%#", [person valueForKey:#"description"]];
if(![str isEqualToString:#"<null>"])
{
NSString *position = [person objectForKey:#"position"];
[tempArray addObject: position];
if(![str2 isEqualToString:#"<null>"])
{
NSString *subcounty = [person objectForKey:#"subcounty"];
[tempArray2 addObject: subcounty];
}
else{
[tempArray2 addObject: #"-"];
}
if(![str3 isEqualToString:#"<null>"])
{
NSString *postDate = [person objectForKey:#"postdate"];
[tempArray3 addObject: postDate];
}
else{
[tempArray3 addObject: #"-"];
}
if(![str4 isEqualToString:#"<null>"])
{
NSString *logo = [person objectForKey:#"logo"];
[tempArray4 addObject: [NSString stringWithFormat:#"http://www.bestitjobs.co.uk/employers/logo/Files/%#", logo]];
}
else{
[tempArray4 addObject: [NSString stringWithFormat:#"http://www.bestitjobs.co.uk/employers/logo/Files/%#", "noimage.gif"]];
}
if(![str5 isEqualToString:#"<null>"])
{
NSString *description = [person objectForKey:#"description"];
[tempArray5 addObject: description];
}
else{
[tempArray5 addObject: #"-"];
}
}
}
if (countPage == 1) {
[self.buttonPrev setEnabled:FALSE];
}
else {
[self.buttonPrev setEnabled:TRUE];
}
NSInteger val = [dataResult intValue];
NSInteger pageEnd = val/10;
if (countPage < pageEnd) {
[self.buttonNext setEnabled:TRUE];
}
else {
[self.buttonNext setEnabled:FALSE];
}
//NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"iPhone", #"iPod",#"iPad",nil];
self.listData = tempArray;
self.listLocation = tempArray2;
self.listPostDate = tempArray3;
self.listLogo = tempArray4;
self.listDescription = tempArray5;
[self.listData release];
[self.listLocation release];
[self.listPostDate release];
[self.listLogo release];
[self.listDescription release];
tempArray = nil;
tempArray2 = nil;
tempArray3 = nil;
tempArray4 = nil;
tempArray5 = nil;
}
- (void)viewDidLoad {
[self loadData];
[super viewDidLoad];
}
- (void)dealloc {
[tempArray dealloc];
[tempArray2 dealloc];
[tempArray3 dealloc];
[tempArray4 dealloc];
[tempArray5 dealloc];
[self.listData dealloc];
[self.listLocation dealloc];
[self.listPostDate dealloc];
[self.listLogo dealloc];
[self.listDescription dealloc];
[super dealloc];
}
#pragma mark -
#pragma mark Table View Data Source Methods
- (IBAction)prev{
countPage = countPage - 1;
[self.listData removeAllObjects];
[self.listLocation removeAllObjects];
[self.listPostDate removeAllObjects];
[self.listLogo removeAllObjects];
//NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"1", #"2",#"3",nil];
//self.listData = array;
[self loadData];
[self.uiTableView reloadData];
}
- (IBAction)next{
countPage = countPage + 1;
[self.listData removeAllObjects];
[self.listLocation removeAllObjects];
[self.listPostDate removeAllObjects];
[self.listLogo removeAllObjects];
//NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"1", #"2",#"3",nil];
//self.listData = array;
[self loadData];
[self.uiTableView reloadData];
}
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
JobAddSiteAppDelegate *ja = (JobAddSiteAppDelegate *)[[UIApplication sharedApplication] delegate];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
for (UIView *view in cell.contentView.subviews){
if ([view isKindOfClass:[UILabel class]]){
UILabel *label = (UILabel *)view;
if (label.tag == 1) {
ja.jobText = label.text;
}
if (label.tag == 2) {
ja.locationText = label.text;
}
if (label.tag == 3) {
ja.dateText = label.text;
}
if (label.tag == 4) {
}
if (label.tag == 5) {
ja.specificText = label.text;
}
}
if ([view isKindOfClass:[UIImageView class]]){
UIImageView *image = (UIImageView *)view;
if (image.tag = 4){
ja.logoText = image.image;
}
}
}
SpecificAddViewController *second = [[SpecificAddViewController alloc]initWithNibName:nil bundle:nil];
[self presentModalViewController:second animated:YES];
[second release];
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [self.listData count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath
*)indexPath
{
if (indexPath.section == 1 && indexPath.row == 1) {
return 65;
}
return 65;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
UILabel *labelMain;
UILabel *labelLocation;
UILabel *labelDate;
UIImageView *image;
UILabel *ref;
if (cell == nil) {
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease];
image = [[[UIImageView alloc] initWithFrame:CGRectMake(0,3,80,62)] autorelease];
image.tag = 4;
[cell.contentView addSubview:image];
labelMain = [[[UILabel alloc] initWithFrame:CGRectMake(90,3,200,20)] autorelease];
labelMain.tag = 1;
labelMain.font = [UIFont systemFontOfSize:14.0];
[cell.contentView addSubview:labelMain];
labelLocation = [[[UILabel alloc] initWithFrame:CGRectMake(90,20,200,20)] autorelease];
labelLocation.tag = 2;
labelLocation.font = [UIFont systemFontOfSize:12.0];
labelLocation.textColor = [UIColor darkGrayColor];
[cell.contentView addSubview:labelLocation];
labelDate = [[[UILabel alloc] initWithFrame:CGRectMake(90,40,200,20)] autorelease];
labelDate.tag = 3;
labelDate.font = [UIFont systemFontOfSize:12.0];
labelDate.textColor = [UIColor darkGrayColor];
[cell.contentView addSubview:labelDate];
ref = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)] autorelease];
ref.tag = 5;
[cell.contentView addSubview:ref];
}
[(UILabel *)[cell.contentView viewWithTag:1] setText:[self.listData objectAtIndex:indexPath.row]];
[(UILabel *)[cell.contentView viewWithTag:2] setText:[self.listLocation objectAtIndex:indexPath.row]];
[(UILabel *)[cell.contentView viewWithTag:3] setText:[self.listPostDate objectAtIndex:indexPath.row]];
[(UILabel *)[cell.contentView viewWithTag:5] setText:[self.listDescription objectAtIndex:indexPath.row]];
NSString *imagePath = [self.listLogo objectAtIndex:indexPath.row];
image.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imagePath]]];
return cell;
}
#end
The call
image.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imagePath]]];
will block the execution thread and being indeterminately long in terms of network use this is a bad thing. Each of your cells needs to wait to the image to load.
Check out "lazy loading of tableView cells" as a research topic.
Instead you should give the URL to the cell and tell it to load the image off the main thread.
as in
[cell loadImageAtURL:someURL];
and within a UITableViewCell subclass implementation
-(void)loadImageAtURL:(NSURL *)aurl
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSData *data = [NSData dataWithContentsOfURL:aurl];
if (data) {
UIImage *image = [UIImage imageWithData:data];
//must update UI on main queue
dispatch_async(dispatch_get_main_queue() ,^{
self.cellImageView = image;
}
}
});
}
Theres also a ton of Obj-C image loaders . EGOCache is my go to library but have a look round.
In summary the cell needs to own the image load process not the tableview because theres no guarantee that the cell will not be reused before the image loads and displays.
NSInteger is a primitive type, which means it can be stored locally on the stack. You don't need to use a pointer to access it. The way you are using it i think is a problem, getting the pointer value instead of the actual value of the primitive type.
I think this is what you want for the declaration/initialization of countPage:
NSInteger countPage = 1;

Index tableview in iphone sdk

i have an indexed tableview with 8 arrays like
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray addObject:#"GEN"];
[tempArray addObject:#"1SA"];
[tempArray addObject:#"EST"];
[tempArray addObject:#"EZE"];
[tempArray addObject:#"NAH"];
[tempArray addObject:#"JOH"];
[tempArray addObject:#"COL"];
[tempArray addObject:#"REV"];
return tempArray;
}
and i get everything right,my problem is when i tap the cell it redirected to the another page with only first array value that is the value inside the [tempArray addObject:#"GEN"];and i tap the values in [tempArray addObject:#"1SA"];etc etc,i get the values inn the [tempArray addObject:#"GEN"];.my DidSelectRowAtIndexPath look like this
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
ChapterSelectionView *detailViewController = [[ChapterSelectionView alloc] initWithNibName:#"ChapterSelectionView" bundle:nil];
//detailViewController.firstString = firstString;
// ...
// Pass the selected object to the new view controller.
detailViewController.selectedIndex=indexPath.row;
detailViewController.selectedCountry = selectedCountry;
appDelegate.selectedBookIndex=indexPath.row;
self.hidesBottomBarWhenPushed=YES;
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
}
this is my complete tableview code
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
return index % 8;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [books count];
}
my viewdidload look like this
- (void)viewDidLoad {
[super viewDidLoad];
l
appDelegate=(Malayalam_BibleAppDelegate *)[[UIApplication sharedApplication] delegate];
s";
books = [[NSMutableArray alloc] init];
NSArray *biblearray1 = [NSArray arrayWithObjects:#"Genesis",
#"Exodus",
#"Leviticus",
#"Numbers",
#"Deuteronomy",
#"Joshua",
#"Judges",
#"Ruth", nil];
NSDictionary *bibledic1 = [NSDictionary dictionaryWithObject:biblearray1 forKey:#"Countries"];
NSArray *biblearray2 = [NSArray arrayWithObjects:#"1Samuel",
#"2Samuel",
#"1King",
#"2King",
#"1Chronicles",
#"2Chronicles",
#"Ezra",
#"Nehemiah", nil];
......etc etc
[books addObject:bibledic1];
[books addObject:bibledic2];
.....etc etc
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSDictionary *dictionary = [books objectAtIndex:section];
NSArray *array = [dictionary objectForKey:#"Countries"];
return [array 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];
}
UIView *myBackView = [[UIView alloc] initWithFrame:cell.frame];
myBackView.backgroundColor = [UIColor brownColor];
// [myBackView setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:0.75 alpha:1]];
cell.selectedBackgroundView = myBackView;
[myBackView release];
// Configure the cell.
// cell.textLabel.tag =row*1+col;
//First get the dictionary object
NSDictionary *dictionary = [books objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"Countries"];
//NSString *cellValue = [array objectAtIndex:indexPath.row];
cell.textLabel.text =[array objectAtIndex:indexPath.row];
cell.textLabel.highlightedTextColor = [UIColor darkGrayColor];
//cell.textLabel.text = [books objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont fontWithName:#"Georgia" size:18.0];
cell.textLabel.textColor = [UIColor darkGrayColor];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;;
return cell;
}
how to get the correct values from tableview cell.
Thanks in advance.
EDIT
- (void)viewDidLoad {
[super viewDidLoad];
[[self navigationController] setNavigationBarHidden:YES animated:NO];
scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0,49,320,480)];
appDelegate = (Malayalam_BibleAppDelegate *)[[UIApplication sharedApplication] delegate];
//self.navigationItem.title=[appDelegate.books objectAtIndex:selectedIndex];
chapterlabel.text = [appDelegate.books objectAtIndex:selectedIndex];
buttonArray =[[NSMutableArray alloc]initWithCapacity:0];
//self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:#"bg10"]];
[self.view addSubview:scrollView];
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:YES];
[[self navigationController] setNavigationBarHidden:YES animated:NO];
n=[DbHandler mNumberOfChaptersInBook:[appDelegate.books objectAtIndex:selectedIndex]];
int scrollViewHieght=n/6;
scrollView.contentSize = CGSizeMake(320,10+34*scrollViewHieght);
i=1;
int rowCount=n/6;
for(int row=0;row<=rowCount;row++){
for (int col = 0; col < 6; col++) {
if(i<=n){
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.titleLabel.textColor=[UIColor blueColor];
button.titleLabel.font = [UIFont fontWithName:#"Georgia" size:15.0];
[button setBackgroundImage:[UIImage imageNamed:#"tabs"] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//button.frame=CGRectMake(col*52+5,row*34+50,50,32);
button.frame=CGRectMake(col*52+5,row*34+0,50,32);
[button addTarget:self action:#selector(ButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:[NSString stringWithFormat:#"%d",i++] forState:UIControlStateNormal];
//button.titleLabel.font=[UIFont boldSystemFontOfSize:15];
button.titleLabel.textColor=[UIColor blackColor];
button.tag =row*6+col;
[buttonArray addObject:button];
[scrollView addSubview:[buttonArray objectAtIndex:row*6+col]];
//[self.view addSubview:button];
[button release];
}
}
}
}
you also need to send section number to the detailViewController. Depending on the section you have to select the required array.

App crashes after custom cell is created 250 times

I use a custom cell in my app. When a user taps a table row, a custom cell appears:
#import "SonaraamatuKontroller.h"
#import "TolkegaLahter.h"
//Lahtris kasutatava teksti fondi suurus
#define FONT_SIZE 14.0f
//Tabelilahtri laius
#define CELL_CONTENT_WIDTH 320.0f
//Tabeli sisu äärise kaugus lahtri servadest
#define CELL_CONTENT_MARGIN 5.0f
#implementation SonaraamatuKontroller
#synthesize sonaraamatuSisukord=sonaraamatuSisukord;
#synthesize sonaraamatuTabel;
#synthesize valitudLahtriIndexPath;
#synthesize tolkegaLahter;
#synthesize audioPleier;
#synthesize sonaraamatuFailinimi;
#synthesize sonaraamatuNavribaNimi;
- (void)viewDidLoad {
[super viewDidLoad];
NSString *error;
NSPropertyListFormat format;
NSString *localizedPath = [[NSBundle mainBundle] pathForResource:sonaraamatuFailinimi ofType:#"plist"];
NSData *plistData = [NSData dataWithContentsOfFile:localizedPath];
NSArray *sisukordData = [NSPropertyListSerialization propertyListFromData:plistData
mutabilityOption:NSPropertyListImmutable
format:&format
errorDescription:&error];
if (sisukordData) {
self.sonaraamatuSisukord = [NSMutableArray arrayWithCapacity:[sonaraamatuSisukord count]];
for (NSDictionary *sisukordDictionary in sisukordData) {
[self.sonaraamatuSisukord addObject:sisukordDictionary];
}
}
self.navigationItem.title=sonaraamatuNavribaNimi;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
//Teise vaatesse liikumisel pannakse audiopleier seisma
[audioPleier stop];
// Release anything that can be recreated in viewDidLoad or on demand.
// e.g. self.myOutlet = nil;
}
#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//Loeme tabeli sektsioonide arvu - kuna praegusel juhul on sisukorras ainult üks liige (sõnaraamat "Item 0"), siis on ka sektsioone üks
return [sonaraamatuSisukord count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//Loeme vastavas sektsioonis asuvate ridade arvu
NSMutableArray *sisukordItems = [[sonaraamatuSisukord objectAtIndex:section] objectForKey:#"Items"];
return [sisukordItems count];
}
- (CGFloat) tableView : (UITableView *) tableView
heightForRowAtIndexPath: (NSIndexPath *) indexPath {
if(valitudLahtriIndexPath != nil
&& [valitudLahtriIndexPath isEqual:indexPath] )
return 95;
NSMutableArray *sisukordItems = [[sonaraamatuSisukord objectAtIndex:indexPath.section] objectForKey:#"Items"];
NSDictionary *sisukordItem = [sisukordItems objectAtIndex:indexPath.row];
NSString *text = [sisukordItem objectForKey:#"Valjend"];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height, 25.0f);
return height + (CELL_CONTENT_MARGIN * 2);
}
#pragma mark -
#pragma mark UITableViewDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if((valitudLahtriIndexPath != nil)
&& [valitudLahtriIndexPath isEqual:indexPath]
)
{ //NSLog (#"ValitudPath: %#", valitudLahtriIndexPath);
static NSString *TolkegaLahtriTunnus = #"TolkegaLahter";
TolkegaLahter *cell = (TolkegaLahter *)[tableView dequeueReusableCellWithIdentifier:TolkegaLahtriTunnus];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"TolkegaLahter" owner:self options:nil];
cell = tolkegaLahter;
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//Lisame gradiendi:
CAGradientLayer *gradient = [CAGradientLayer layer];
[gradient setCornerRadius:9.0f];
//[gradient setMasksToBounds:YES];
//[gradient setBorderWidth:0.8f];
//[gradient setBorderColor:[[UIColor darkGrayColor] CGColor]];
gradient.frame = cell.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:0.122 green:0.2 blue:1 alpha:0.95] CGColor], (id)[[UIColor colorWithRed:0.041 green:0.1 blue:0.33 alpha:0.95] CGColor],(id)[[UIColor colorWithRed:0.122 green:0.2 blue:1 alpha:0.95] CGColor], nil];
gradient.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0],[NSNumber numberWithFloat:0.48],[NSNumber numberWithFloat:1.0], nil];
[cell.layer insertSublayer:gradient atIndex:0];
}
NSMutableArray *sisukordItems = [[sonaraamatuSisukord objectAtIndex:indexPath.section] objectForKey:#"Items"];
NSDictionary *sisukordItem = [sisukordItems objectAtIndex:indexPath.row];
cell.valjend.text=[sisukordItem objectForKey:#"Valjend"];
cell.tolge.text=[sisukordItem objectForKey:#"Tolge"];
[sonaraamatuTabel scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:YES];
self.tolkegaLahter = nil;
return cell;
}
static NSString *CellIdentifier = #"Cell";
//Loome lahtrisse labeli
UILabel *label = nil;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//Esialgu on label tühi (asub punktis 0,0 ning on suurusega 0,0)
label = [[UILabel alloc] initWithFrame:CGRectZero];
//Määrame reavahetuse stiili
[label setLineBreakMode:UILineBreakModeWordWrap];
//Minimaalne fondi suurus on ülal defineeritud konstant
[label setMinimumFontSize:FONT_SIZE];
//Esialgu on ridade arv 0
[label setNumberOfLines:0];
//Määrame fondi. Selle suuruseks on ülal defineeritud konstant
[label setFont:[UIFont systemFontOfSize:FONT_SIZE]];
[label setTag:1];
//Lisame labelile piirid, et programmeerimise käigus oleks paremini näha, kuhu see lahtris paigutub
//[[label layer] setBorderWidth:2.0f];
[[cell contentView] addSubview:label];
[label release];
}
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.selectedBackgroundView=[[[UIView alloc] init] autorelease];
cell.selectedBackgroundView.backgroundColor=[UIColor colorWithRed:0.537 green:0.18 blue:0.122 alpha:1.0];
//Loome andmemassiivi sisukord objektidest (tuntakse ära võtme "Items" abil) andmemassiivi sisukordItems
NSMutableArray *sisukordItems = [[sonaraamatuSisukord objectAtIndex:indexPath.section] objectForKey:#"Items"];
//Loome andmemassiivi sisukordItems objektidest sõnaraamatud sisukordItem
NSDictionary *sisukordItem = [sisukordItems objectAtIndex:indexPath.row];
//Igas lahtris kuvatakse sellele vastavas sõnaraamatus sisalduva objekti "Valjend" väärtus
NSString *text = [sisukordItem objectForKey:#"Valjend"];
//Sarnaselt lahtri kõrguse arvutamisele heightForRowAtIndexPath meetodis arvutame ka labeli
//kõrguse (sellele ei liideta ääriste kaugusi)
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
//Hangime labeli juhul kui see on nil (ja tegu ei ole vaate esialgse initsieerimisega ehk lahter ei ole nil)
if (!label)
label = (UILabel*)[cell viewWithTag:1];
//Seame labeli teksti
[label setText:text];
//Seame labeli piirjooned
[label setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 25.0f))];
label.textColor=[UIColor blackColor];
label.font=[UIFont systemFontOfSize:14];
label.backgroundColor=[UIColor clearColor];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
self.valitudLahtriIndexPath = indexPath;
if(valitudLahtriIndexPath != nil //Kui see väärtus on tõene,
&& [valitudLahtriIndexPath isEqual:indexPath]) {
[self.sonaraamatuTabel reloadData];
NSMutableArray *sisukordItems = [[sonaraamatuSisukord objectAtIndex:indexPath.section] objectForKey:#"Items"];
NSDictionary *sisukordItem = [sisukordItems objectAtIndex:indexPath.row];
NSString*heliFailinimi=[sisukordItem objectForKey:#"HeliFailinimi"];
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
NSString *taustaHeliPath = [[NSBundle mainBundle] pathForResource:heliFailinimi ofType:#"m4a"];
[audioPleier stop];
NSURL *taustaHeliURL = [NSURL fileURLWithPath:taustaHeliPath];
NSError *error;
audioPleier = [[AVAudioPlayer alloc] initWithContentsOfURL:taustaHeliURL error:&error];
[audioPleier setDelegate:self]; // We need this so we can restart after interruptions
[audioPleier play];
}
}
- (void)viewWillAppear:(BOOL)animated
{
NSIndexPath*selection = [self.sonaraamatuTabel indexPathForSelectedRow];
if (selection)
[self.sonaraamatuTabel deselectRowAtIndexPath:selection animated:YES];
[self.sonaraamatuTabel reloadData];
}
- (void)dealloc {
[valitudLahtriIndexPath release];
[sonaraamatuSisukord release], sonaraamatuSisukord=nil;
[audioPleier release];
[sonaraamatuFailinimi release];
[sonaraamatuNavribaNimi release];
[super dealloc];
}
#end
After 250 taps the app crashes and I get the message:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle (loaded)' with name 'TolkegaLahter''
What could be the reason of this behaviour? A memory leak somewhere?
EDIT
It was about the AVAudioPlayer, which was created again and again, but not released.
So, I replaced
audioPleier = [[AVAudioPlayer alloc] initWithContentsOfURL:taustaHeliURL error:&error];
with
AVAudioPlayer*ajutineAudioPleier = [[AVAudioPlayer alloc] initWithContentsOfURL:taustaHeliURL error:&error];
self.audioPleier=ajutineAudioPleier;
[ajutineAudioPleier release];
Is the code in your question the cellForRowAtIndexPath method? It isn't clear from your question whereabouts this code is or when it is executed.
If it is (or, for some of these, even if it isn't) there are a couple of problems with it:
You aren't returning the cell if the dequeue method brings you something back
You aren't configuring the cell if the dequeue method brings you something back
Which leads me to expect that you haven't set the reuse identifier in your custom cell subclass in interface builder
Which means you are creating a new cell each time which could give you a crash if you have a sufficient number of cells
The scrolling call seems odd (this would only be odd if this was your cellForRowAtIndexPath method)
If you are repeatedly loading from nibs you may want to check out UINib as well.
EDIT
After looking at your full code, I think the problem is your audio player, you are creating and configuring a new one every time the cell is selected and this is leaking.
You should just set up the audio player on your viewDidLoad, and just tell it to play the specific sound when you select the cell.
Try to replace
[[NSBundle mainBundle] loadNibNamed:#"TolkegaLahter" owner:self options:nil];
cell = tolkegaLahter;
to
cell = [[[TolkegaLahter alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: TolkegaLahtriTunnus] autorelease];
self.tolkegaLahter = [[[NSBundle mainBundle] loadNibNamed:#"TolkegaLahter" owner:self options:nil] lastObject];
cell = self.tolkegaLahter;

Crash after returning to tableview

So I am writing an app to read an rss feed, and display the contents in a tableview. It also lets the user play back mp3s that it finds for each item. Anyway the app seemed to be running fine before I started adding new views. Now every time I come back from a view and scroll around a bit, I get "Program received signal "SIGABRT"" or something similar.
here's most of the program:
- (IBAction)playAction:(id)sender
{
// Get row
UIButton *senderButton = (UIButton *)sender;
UITableViewCell *buttonCell =
(UITableViewCell *) [[senderButton superview] superview];
NSInteger buttonRow = [[self.tableView
indexPathForCell:buttonCell] row];
// Entry for row
RSSEntry *senderEntry = [_allEntries objectAtIndex:buttonRow];
// This is where _allEntries gets filled
- (void)requestFinished:(ASIHTTPRequest *)request {
[_queue addOperationWithBlock:^{
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
options:0 error:&error];
if (doc == nil)
{
NSLog(#"Failed to parse %#", request.url);
}
else
{
NSMutableArray *entries = [NSMutableArray array];
[self parseRss:doc.rootElement entries:entries];
if ([_allEntries count] > 0) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// Update
int i=0;
while (![[[_allEntries objectAtIndex:i] articleUrl] isEqualToString:[[entries objectAtIndex:i] articleUrl]])
{
[_allEntries insertObject:[entries objectAtIndex:i] atIndex:0];
i++;
}
[self.tableView reloadData];
}];
}
else
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries)
{
[_allEntries addObject:entry];
}
NSLog(#"entries:%d", [_allEntries count]);
[self.tableView reloadData];
}];
}
}
}];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"View did load");
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refreshButton:)];
pauseImage = [UIImage imageNamed:#"pause_circle_small.png"];
playImage = [UIImage imageNamed:#"play_circle_small.png"];
player = nil;
isPlaying = NO;
self.title = #"Feed";
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feed = [[NSString alloc] initWithString:#"http://site.org/rss/"];
[self refresh];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [_allEntries count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UILabel *mainLabel, *secondLabel;
UIButton *playBtn;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(42.0, 5.0, 250.0, 20.0)] autorelease];
mainLabel.tag = MAINLABEL_TAG;
mainLabel.font = [UIFont fontWithName:#"Arial-BoldMT" size:18.0];
mainLabel.textAlignment = UITextAlignmentLeft;
mainLabel.textColor = [UIColor blackColor];
mainLabel.highlightedTextColor = [UIColor whiteColor];
[cell.contentView addSubview:mainLabel];
secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(42.0, 27.0, 250.0, 15.0)] autorelease];
secondLabel.tag = SECONDLABEL_TAG;
secondLabel.font = [UIFont fontWithName:#"ArialMT" size:14.0];
secondLabel.textAlignment = UITextAlignmentLeft;
secondLabel.textColor = [UIColor colorWithRed:222.0/255.0 green:95.0/255.0
blue:199.0/255.0 alpha:1.0];
secondLabel.highlightedTextColor = [UIColor whiteColor];
[cell.contentView addSubview:secondLabel];
playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
playBtn.tag = PLAYBTN_TAG;
playBtn.frame = CGRectMake(2.0, 6.0, playImage.size.width, playImage.size.height);
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
//[playBtn setBackgroundImage:playImage forState:UIControlStateHighlighted];
[playBtn addTarget:self action:#selector(playTapped:)
forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:playBtn];
}
else
{
mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];
secondLabel = (UILabel *)[cell.contentView viewWithTag:SECONDLABEL_TAG];
playBtn = (UIButton *)[cell.contentView viewWithTag:PLAYBTN_TAG];
}
// Alternate bg color
if (indexPath.row%2 == 0) {
UIColor *altColor = [UIColor colorWithRed:230.0/255.0 green:230.0/255.0
blue:230.0/255.0 alpha:1];
mainLabel.backgroundColor = altColor;
secondLabel.backgroundColor = altColor;
}
else
{
UIColor *altColor = [UIColor colorWithRed:255.0 green:255.0
blue:255.0 alpha:1];
mainLabel.backgroundColor = altColor;
secondLabel.backgroundColor = altColor;
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSLog(#"Entry: %#", entry);
// Manage play button
if (entry == currEntry)
{
if(isPlaying)
{
[playBtn setBackgroundImage:pauseImage forState:UIControlStateNormal];
}
else
{
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
}
}
else
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
mainLabel.text = entry.articleTitle;
secondLabel.text = entry.articleArtist;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
DetailView *detailViewController = [[DetailView alloc] initWithNibName:#"DetailedView" bundle:[NSBundle mainBundle]];
RSSEntry *entry = [_allEntries objectAtIndex:[indexPath row]];
[self.navigationController pushViewController:detailViewController animated:YES];
detailViewController.songTitle.text = entry.articleTitle;
detailViewController.artistName.text = entry.articleArtist;
[entry release];
[detailViewController release];
}
- (void)dealloc
{
[player release];
player = nil;
[_queue release];
_queue = nil;
[_feed release];
_feed = nil;
[_allEntries release];
_allEntries = nil;
[super dealloc];
}
#end
Please Dont release any #synthesize variable. You should only release it in dealloc method
It's a wild guess, but you don't retain the images that you get in viewDidLoad:
pauseImage = [UIImage imageNamed:#"pause_circle_small.png"];
playImage = [UIImage imageNamed:#"play_circle_small.png"];
Either use retaining property and dot syntax or send each a retain.
AHAA!!! I was setting my RSSEntry to autorelease before putting them in the _allEntries array. They were getting dealloc'd when I changed views. Don't do that. Thanks for the help everyone. That was so simple, I feel dumb now.
please don't release the self.feed and also when unload or dealloc the view at that time put delegate nil means
tableview.delegate = nil;
this one is the main thing check after this i think u don't nil the delegate of tableview.
without line where you get crash its hard to tell, but most likely you accessing some object what was dealloc'ed
most likely its here
self.feed = [[NSString alloc] initWithString:#"http://site.org/rss/music"];
[self.feed release];
you releasing objects right away, but its hard to tell without knowing if you have retained property

UILabel wrong release into UITableViewCell

I have a custom UITableViewCel like this:
#synthesize poiNameLabel;
#synthesize poiDistanceLabel;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
// Initialization code
CGRect nlabelframe = CGRectMake(NAMELABEL_X, NAMELABEL_Y, NAMELABEL_WIDTH, NAMELABEL_HEIGHT);
UILabel *nlabel = [[UILabel alloc] initWithFrame:nlabelframe];
nlabel.font = [UIFont fontWithName:#"Arial" size:NAMELABEL_FONT];
nlabel.backgroundColor = [UIColor clearColor];
nlabel.minimumFontSize = NAMELABEL_FONT_MIN;
//nlabel.adjustsFontSizeToFitWidth = YES;
[self addSubview:nlabel];
self.poiNameLabel = nlabel;
[nlabel release];
CGRect dlabelframe = CGRectMake(DISTANCELABEL_X, DISTANCELABEL_Y, DISTANCELABEL_WIDTH, DISTANCELABEL_HEIGHT);
UILabel *dlabel = [[UILabel alloc] initWithFrame:dlabelframe];
dlabel.font = [UIFont fontWithName:#"Arial" size:DISTANCELABEL_FONT];
dlabel.backgroundColor = [UIColor clearColor];
dlabel.minimumFontSize = DISTANCELABEL_FONT_MIN;
dlabel.adjustsFontSizeToFitWidth = YES;
[self addSubview:dlabel];
self.poiDistanceLabel = dlabel;
[dlabel release];
self.contentView.backgroundColor = [UIColor clearColor];
self.contentView.opaque = NO;
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}
- (void)dealloc {
[super dealloc];
[poiNameLabel release];
[poiDistanceLabel release];
}
and this is how I fill it:
NSDictionary *dic = [[NSDictionary alloc] initWithDictionary:[poisSource objectAtIndex:row]];
ResultsViewCell *cell = [[[ResultsViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.poiNameLabel.text = [dic objectForKey:#"name"];
float distance = [[dic objectForKey:#"distance"] floatValue];
NSString *distanceWithUnity;
distance = distance*1000;
if (distance > 1000) {
distanceWithUnity = [NSString stringWithFormat:#"%.2f km", distance/1000];
} else {
distanceWithUnity = [NSString stringWithFormat:#"%.0f mt", distance];
}
cell.poiDistanceLabel.text = distanceWithUnity;
[dic release];
return cell;
Everything is ok, but when the UITableCell is deallocated, I get BAD_ACCESS releasing poiDistanceLabel.
I see no problem in my code, no retain errors, so I can't understand what's happening.
The only doubt I have is about how I'm setting the label text: can this be the issue? Why is this happening?
Problem seems to be in your dealloc method:
[super dealloc]
should be the last call in your dealloc method to keep object "alive" while it is deallocating.