Crash after returning to tableview - iphone

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

Related

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.

How can I search data from tableview cell?

I have an UITableview controller which representing fetched XML data. For representing these data I used five UILabel. Now I have to add a searchbar at the top of the UITableview. So programmatically I have added a searchbar.
Now I have used searching theorem for search data from the UITableview. But It is not working. I can search data from UItableview when only one text in the UItableviewcell without any UIlabel or something else but in my UItableviewcell cell are taking five UILabel that's why it's becoming tough for me to search data from the UItableviewcell. For understanding I am attaching my code how I am representing my XML data in tableview cell.
This is my XML data representation in UITableviewCell...
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:15.0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrow.png"]];
cell.accessoryView = imageView;
cell.accessoryType = UITableViewCellSelectionStyleNone;
tableView.separatorColor = [UIColor clearColor];
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
cellView = [[[UIView alloc] initWithFrame:CGRectMake(5,8,290, 120)] autorelease];
cellView.backgroundColor = [UIColor clearColor];
cellView.tag =10;
[cell.contentView addSubview:cellView];
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(2, 40, 48, 48)];
imgView.image = [UIImage imageNamed:#"productbox.png"];
imgView.layer.borderColor = [UIColor blackColor].CGColor;
imgView.layer.borderWidth = 2.0;
imgView.tag = 5;
[cellView addSubview:imgView];
CGRect idLabelRect = CGRectMake(65, 0, 190, 18);
idLabel = [[[UILabel alloc] initWithFrame:idLabelRect] autorelease];
idLabel.textAlignment = UITextAlignmentLeft;
idLabel.textColor = [UIColor blackColor];
idLabel.font = [UIFont systemFontOfSize:12];
idLabel.backgroundColor = [UIColor clearColor];
idLabel.layer.borderColor = [UIColor grayColor].CGColor;
idLabel.tag = 0;
CGRect statusRect = CGRectMake(65, 22, 190, 22);
statusLabel = [[[UILabel alloc] initWithFrame:statusRect] autorelease];
statusLabel.textAlignment = UITextAlignmentLeft;
statusLabel.textColor = [UIColor blackColor];
statusLabel.font = [UIFont systemFontOfSize:12];
statusLabel.backgroundColor = [UIColor clearColor];
statusLabel.layer.borderColor = [UIColor grayColor].CGColor;
statusLabel.tag = 1;
CGRect orderDateRect = CGRectMake(65, 48, 190, 22);
orderDate = [[[UILabel alloc] initWithFrame:orderDateRect] autorelease];
orderDate.textAlignment = UITextAlignmentLeft;
orderDate.textColor = [UIColor blackColor];
orderDate.font = [UIFont systemFontOfSize:12];
orderDate.backgroundColor = [UIColor clearColor];
orderDate.layer.borderColor = [UIColor grayColor].CGColor;
orderDate.tag = 2;
CGRect byRect = CGRectMake(65, 75, 190, 22);
byLabel = [[[UILabel alloc] initWithFrame:byRect] autorelease];
byLabel.textAlignment = UITextAlignmentLeft;
byLabel.textColor = [UIColor blackColor];
byLabel.font = [UIFont systemFontOfSize:12];
byLabel.backgroundColor = [UIColor clearColor];
byLabel.layer.borderColor = [UIColor grayColor].CGColor;
byLabel.tag = 3;
CGRect totalRect = CGRectMake(65, 98, 190, 22);
totalLabel = [[[UILabel alloc] initWithFrame:totalRect] autorelease];
totalLabel.textAlignment = UITextAlignmentLeft;
totalLabel.textColor = [UIColor blackColor];
totalLabel.font = [UIFont systemFontOfSize:12];
totalLabel.backgroundColor = [UIColor clearColor];
totalLabel.layer.borderColor = [UIColor grayColor].CGColor;
totalLabel.tag = 4;
[cellView addSubview:idLabel];
[cellView addSubview:statusLabel];
[cellView addSubview:orderDate];
[cellView addSubview:byLabel];
[cellView addSubview:totalLabel];
}
if(searching == YES){
//[cell setText:[tableData objectAtIndex:indexPath.row]];
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
}
else{
cellView = (UIView *)[cell.contentView viewWithTag:10];
idLabel = (UILabel *)[cellView viewWithTag:0];
statusLabel = (UILabel *)[cellView viewWithTag:1];
orderDate = (UILabel *)[cellView viewWithTag:2];
byLabel = (UILabel *)[cellView viewWithTag:3];
totalLabel = (UILabel *)[cellView viewWithTag:4];
imgView = (UIImageView *)[cellView viewWithTag:5];
if(pendingOrder == NO && todaysOrder == NO){
idLabel.text = [NSString stringWithFormat:#"Order Id: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:0]];
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:1]];
orderDate.text = [NSString stringWithFormat:#"Date: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:2]];
byLabel.text =[NSString stringWithFormat:#"By: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:3]];
totalLabel.text =[NSString stringWithFormat:#"Total: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:4]];
}
else if(pendingOrder == YES && todaysOrder == NO){
idLabel.text = [NSString stringWithFormat:#"Order Id: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:0]];
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:1]];
orderDate.text = [NSString stringWithFormat:#"Date: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:2]];
byLabel.text =[NSString stringWithFormat:#"By: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:3]];
totalLabel.text =[NSString stringWithFormat:#"Total: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:4]];
}
}
return cell;
}
And this searching Delegate.....
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
searching = YES;
// only show the status bar’s cancel button while in edit mode
sBar.showsCancelButton = YES;
sBar.autocorrectionType = UITextAutocorrectionTypeNo;
// flush the previous search content
[tableData removeAllObjects];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
searching = NO;
sBar.showsCancelButton = NO;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
[tableData removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:#""] && searchText==nil){
[tableview reloadData];
return;
}
NSInteger counter = 0;
for(NSString *name in dataSource)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
NSRange r = [name rangeOfString:searchText];
if(r.location != NSNotFound)
{
if(r.location== 0)//that is we are checking only the start of the names.
{
[tableData addObject:name];
}
}
counter++;
[pool release];
}
[tableview reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
// if a valid search was entered but the user wanted to cancel, bring back the main list content
[tableData removeAllObjects];
searching = NO;
[tableData addObjectsFromArray:dataSource];
#try{
searching = NO;
[tableview reloadData];
}
#catch(NSException *e){
}
[sBar resignFirstResponder];
sBar.text = #"";
}
// called when Search (in our case “Done”) button pressed
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[sBar resignFirstResponder];
}
For more help to understand i am also attaching my viewDidLoad....
//Add the search bar
sBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,0,320,50)];
sBar.delegate = self;
searching = NO;
[self.view addSubview:sBar];
tableview.dataSource = self;
tableview.delegate = self;
//initialize the two arrays; datasource will be initialized and populated by appDelegate
searchData = [[NSMutableArray alloc] init];
tableData = [[NSMutableArray alloc] init];
[tableData addObjectsFromArray:dataSource];//on launch it should display all the records
Edit
This is my edited portion of numberOfSectionsInTableView and numberOfRowsInSection...
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if(searching == YES){
searching = NO;
sectionCount = [tableData count];
}
else {
if(pendingOrder == NO && todaysOrder == NO){
sectionCount = [records count];
NSLog(#"section cout: %d",sectionCount);
}
else if(pendingOrder == YES && todaysOrder == NO){
//Total pending order counting
sectionCount = [pendingRecords count];
NSLog(#"section cout for pending: %d",sectionCount);
}
else if(pendingOrder == NO && todaysOrder == YES){
NSLog(#"todays order number counting");
}
}
return sectionCount;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
Try this:-
copylistofItem is NSMutableArray copying data that matched with search bar criteria.
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
int i=0
for (NSString *str in [records objectAtIndex:indexPath.i] objectAtIndex:0])
{
[searchArray addObject:str];
i++;
}
for (NSString *sTemp in searchArray)
{
NSString *txtToSearch =[[NSString alloc] initWithString:[sTemp substringWithRange:NSMakeRange(0,[searchText length])]];
if([[txtToSearch lowercaseString] isEqualToString:[searchText lowercaseString]])
{
[copyListOfItems addObject:sTemp];
}
}
[searchArray release];
searchArray = nil;
}
Also we want to know what you have written in your numberOfSections tableView Delegate.

iPhone and Twitter API OAuth Consumer Keys and Secrets

I have a issue while loading my data from Twitter. The method I posted below works for about 5-10 minutes then it freezes up my consumer keys....
I know it is the keys because I have the app already installed on the device working then I will make changes and run on the simulator and it affects the device as well. This last for about 30 minutes then the keys seem to refresh themselves and work without any changes to the actual code. Sometimes I will just go in Twitter Dev were my application is and reset the keys and replace the keys in my code and that works for about 10 minutes then the same thing happens!
Here is the code I am using to call out to twitter OAuth and receive the objects for my UITableView.
- (void)viewDidAppear:(BOOL)animated
{
if(_engine) return;
_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate:self];
_engine.consumerKey = #"key";
_engine.consumerSecret = #"key";
UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine: _engine delegate: self];
if (controller)
[self presentModalViewController: controller animated: YES];
else
{
userAvatar.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://a2.twimg.com/profile_images/1361674958/Wintboard_200px.png" ]]];
tweets = [[NSMutableArray alloc] init];
authors = [[NSMutableArray alloc] init];
avatarsURL =[[NSMutableArray alloc] init];
friendsCount = [[NSMutableArray alloc] init];
followerCount = [[NSMutableArray alloc] init];
retweetCount = [[NSMutableArray alloc] init];
//retweetCount = [[NSMutableArray alloc] init];
[self updateStream:nil];
[progressView.view removeFromSuperview];
}
}
#pragma mark IBActions
-(IBAction)updateStream:(id)sender
{
// [_engine sendUpdate:[textfield text]];
[_engine getFollowedTimelineSinceID:0 startingAtPage:0 count:100];
//[_twitter getFollowedTimelineSinceID:0 startingAtPage:0 count:0];
NSString *path = [[NSBundle mainBundle] pathForResource:#"unlock" ofType:#"caf"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
}
-(IBAction)tweet:(id)sender
{
[_engine sendUpdate:[textfield text]];
[self updateStream:nil];
if (textfield isFirstResponder])
{
textfield.text = #"";
[textfield resignFirstResponder];
}
}
-(BOOL)textFieldShouldClear:(UITextField*)textfield
{
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
// the user pressed the "Done" button, so dismiss the keyboard
[textField resignFirstResponder];
return YES;
}
// Return YES for supported orientations
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation) interfaceOrientation
{
return YES;
}
#pragma mark UITableViewDataSource Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// [_engine sendUpdate:[textfield text]];
[_engine getFollowedTimelineSinceID:0 startingAtPage:0 count:100];
int count = [tweets count];
int count2 = [authors count];
int count3 = [avatarsURL count];
//Return just enough cells to fill the screen during loading ....
if (count == 0)
count = MyCustomRowCount;
return count = 100;
return count2 = 100;
return count3 = 100;
// return count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier] autorelease];
}
/*
//Here it adds a nice shadow to the table view but will crash on rotation and send a wird dump
tableView.layer.shadowColor = [[UIColor blackColor] CGColor];
tableView.layer.shadowOffset = CGSizeMake(1.0f, 1.0f);
tableView.layer.shadowRadius = 8.0f;
tableView.layer.shadowOpacity = 1.0f;
*/
[cell.textLabel setNumberOfLines:1];
[cell.textLabel setText:[(Tweet*)[authors objectAtIndex:indexPath.row] author]];
[cell.detailTextLabel setText:[(Tweet*)[tweets objectAtIndex:indexPath.row] tweet]];
[cell.detailTextLabel setNumberOfLines:10];
[cell.textLabel setTextColor:[UIColor darkGrayColor]];
[cell.textLabel setShadowColor:[UIColor whiteColor]];
[cell.textLabel setShadowOffset:CGSizeMake(0.5, 0.5)];
[cell.detailTextLabel setTextColor:[UIColor blackColor]];
//[cell.detailTextLabel setText:[(Tweet*)[retweetCount objectAtIndex:indexPath.row] reTweetCount]];
[cell.textLabel setUserInteractionEnabled:YES];
[cell.contentView setMultipleTouchEnabled:YES];
// Here we use the new provided setImageWithURL: method to load the web image with SDWebImageManager
[cell.imageView setImageWithURL:[NSURL URLWithString:[(Tweet*)[avatarsURL objectAtIndex:indexPath.row]avatarURL]]
placeholderImage:[UIImage imageNamed:#"avatar.png"]];
//add gradient to cell
UIImage *gradient = [UIImage imageNamed:#"gradientcell2.png"];
UIImageView *cellimage = [[UIImageView alloc] initWithImage:gradient];
cellimage.contentMode = UIViewContentModeScaleToFill;
cell.backgroundView = cellimage;
[cellimage release];
UIImage *selectedGradient = [UIImage imageNamed:#"selectedcell.png"];
UIImageView *selectedCell = [[UIImageView alloc] initWithImage:selectedGradient];
selectedCell.contentMode = UIViewContentModeScaleToFill;
cell.selectedBackgroundView = selectedCell;
[tableView setBackgroundColor:[UIColor clearColor]];
return cell;
}
Yes Sorry I should have came back and answered this!
First make sure your requests are not going over Twitters API request Limit, I was simply while reloading my table view.
After Fixing that mistake I the proceeded to reset my keys wrote a request to Twitter API to use xAuth "it only takes a few days to be accepted" then I have not had any issues since.
I did not use my keys until I received the letter from Twitter saying I was accepted and I have not had any issues since.
I hope this helps because I know how frustrating that can become !
Good Luck!

Checkbox selecting other checkboxes when one is selected

I have created a custom class called Checkbox which changes its image on touch so that it gives a checkbox effect. However, when I click on one checkbox in the tableView, other checkboxes on seperate rows are selected too. Please could you tell me the problem with my code:
Checkbox.m
- (void)checkImages {
NSUInteger tag = [self tag];
BOOL val = [[NSUserDefaults standardUserDefaults] boolForKey:[NSString stringWithFormat:#"%i", tag]];
if (val == YES) {
[self setImage:[UIImage imageNamed:#"checkbox-pressed.png"] forState:UIControlStateNormal];
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:[NSString stringWithFormat:#"%i", tag]];
}
else if (val == NO) {
[self setImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:[NSString stringWithFormat:#"%i", tag]];
}
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if ([[[[event allTouches] anyObject] view] tag] == [self tag]) {
[self checkImages];
}
}
RootViewController:
- (void)viewDidLoad
{
//This will set a solid background color
self.tableView.backgroundColor = [UIColor blackColor];
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
if (_checkboxArray == nil) {
[self setItemArray:[[NSMutableArray alloc] init]];
}
if (_cellTextArray == nil) {
[self setCellTextArray:[[NSMutableArray alloc] init]];
}
if (![[NSUserDefaults standardUserDefaults] boolForKey:kFL]) {
NSMutableArray *custArr = [[NSMutableArray alloc] init];
for (int i = 0; i < [_checkboxArray count]; i ++) {
CheckBox *c = (CheckBox *)[_checkboxArray objectAtIndex:i];
[c setImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:[NSString stringWithFormat:#"%i", [c tag]]];
[custArr addObject:c];
}
[_checkboxArray release];
[_checkboxArray setArray:custArr];
[custArr release];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:kFL];
[[NSUserDefaults standardUserDefaults] synchronize];
}
for (int i = 0; i < [textLabelArray count]; i++) {
NSDictionary *dict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:[textLabelArray objectAtIndex:i], [detailTextArray objectAtIndex:i], [cornLabelArray objectAtIndex:i], nil] forKeys:[NSArray arrayWithObjects:#"textLabel", #"detailTextLabel", #"cornerLabel", nil]];
[_cellTextArray addObject:dict];
[dict release];
}
for (int i = 0; i < [_cellTextArray count]; i++) {
CheckBox*btn = [[CheckBox alloc] init];
[btn setFrame:CGRectMake(0, 10, 40, 40)];
[btn setTag:i];
UIImage *img = [UIImage imageNamed:[[NSUserDefaults standardUserDefaults] boolForKey:[NSString stringWithFormat:#"%i", btn.tag]] ? #"checkbox.png":#"checkbox-pressed.png"];
[btn setImage:img forState:UIControlStateNormal];
[_checkboxArray addObject:btn];
[btn release];
}
[self.tableView reloadData];
[super viewDidLoad];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
CheckBox *btn;
UILabel *lab, *dlabl, *cornerLabel;
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
btn = (CheckBox *)[_checkboxArray objectAtIndex:indexPath.row];
[cell.contentView addSubview:btn];
//I added this code:
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:12.0];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 3; // 0 means no max.
UIImageView* img = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"gradient7.png"]] autorelease];
[cell setBackgroundView:img];
lab = [[[UILabel alloc] initWithFrame:CGRectMake(40, 18, cell.contentView.frame.size.width-15, 22)] autorelease];
[lab setBackgroundColor:[UIColor clearColor]];
[lab setTextColor:[UIColor whiteColor]];
[lab setAdjustsFontSizeToFitWidth:YES];
[lab setTextAlignment:UITextAlignmentLeft];
[lab setTag:kTEXT_LABEL_TAG];
[cell.contentView addSubview:lab];
dlabl = [[[UILabel alloc] initWithFrame:CGRectMake(5, 54, cell.contentView.frame.size.width- 1, 22)] autorelease];
[dlabl setTextColor:[UIColor colorWithRed:1.0 green:0.80 blue:0.0 alpha:1.0]];
[dlabl setBackgroundColor:[UIColor clearColor]];
// [dlabl setAdjustsFontSizeToFitWidth:YES];
[dlabl setTextAlignment:UITextAlignmentLeft];
[dlabl setTag:kDETAIL_TEXT_LABEL_TAG];
[dlabl setFont:[UIFont systemFontOfSize:[lab font].pointSize - 3]];
[cell.contentView addSubview:dlabl];
cornerLabel = [[[UILabel alloc] initWithFrame:CGRectMake(cell.contentView.frame.size.width - 40, 19, 40, 20)] autorelease];
[cornerLabel setTextColor:[UIColor whiteColor]];
//[cornerLabel setFont:[UIFont systemFontOfSize:12]];
[cornerLabel setAdjustsFontSizeToFitWidth:YES];
[cornerLabel setBackgroundColor:[UIColor clearColor]];
[cornerLabel setTextAlignment:UITextAlignmentCenter];
[cornerLabel setTag:kCORNER_TEXT_LABEL_TAG];
[cell.contentView addSubview:cornerLabel];
[cornerLabel setAdjustsFontSizeToFitWidth:YES];
}
else {
lab = (UILabel *)[[cell contentView] viewWithTag:kTEXT_LABEL_TAG];
dlabl = (UILabel *)[[cell contentView] viewWithTag:kDETAIL_TEXT_LABEL_TAG];
cornerLabel = (UILabel *)[[cell contentView] viewWithTag:kCORNER_TEXT_LABEL_TAG];
btn = (CheckBox *)[[cell contentView] viewWithTag:kBTN_TAG];
}
NSDictionary *dict = [_cellTextArray objectAtIndex:indexPath.row];
lab.text = [dict objectForKey:#"textLabel"];
dlabl.text = [dict objectForKey:#"detailTextLabel"];
cornerLabel.text = [dict objectForKey:#"cornerLabel"];
if ([[NSUserDefaults standardUserDefaults] boolForKey:[NSString stringWithFormat:#"%d", indexPath.row]] == NO) {
[btn setImage:[UIImage imageNamed:#"checkbox-pressed.png"] forState:UIControlStateNormal];
}else {
[btn setImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 80.0f;
}
You are using tableView dequeueReusableCellWithIdentifier:CellIdentifier]. This is a good thing, but it means that in your table view, you have only as many cells as you can see. When you scroll and a cell leaves the screen on one end, it will then be reused and reenter the screen from the other end. And of course, the cell still contains the same checkbox, so if it was checked when it left the screen it still will be, if not, it won't.
Solving this should be pretty straight forward. In your tableView:(UITableView *)tableView cellForRowAtIndexPath: you already fill the cell accordingly to the item which should be displayed there (lab.text = [dict objectForKey:#"textLabel"]; and so on). So all you have to to is to save the checkboxes state for every item in your tableview and restore it there.
Hope that helps!

AsyncImage get picture from program source?

from this code
#import "AsyncImageView.h"
#import "ImageCache.h"
#import "ImageCacheObject.h"
static ImageCache *imageCache = nil;
#implementation AsyncImageView
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
}
return self;
}
- (void)drawRect:(CGRect)rect {
// Drawing code
}
- (void)dealloc {
[connection cancel];
[connection release];
[data release];
[super dealloc];
}
-(void)loadImageFromURL:(NSURL*)url {
if (connection != nil) {
[connection cancel];
[connection release];
connection = nil;
}
if (data != nil) {
[data release];
data = nil;
}
if (imageCache == nil)
imageCache = [[ImageCache alloc] initWithMaxSize:2*1024*1024];
[urlString release];
urlString = [[url absoluteString] copy];
UIImage *cachedImage = [imageCache imageForKey:urlString];
if (cachedImage != nil)
{ NSLog(#"get in");
if ([[self subviews] count] > 0)
{
[[[self subviews] objectAtIndex:0] removeFromSuperview];
}
UIImageView *imageView = [[[UIImageView alloc] initWithImage:cachedImage] autorelease];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.autoresizingMask =
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self addSubview:imageView];
imageView.frame = self.bounds;
[imageView setNeedsLayout];
[self setNeedsLayout];
return;
}
#define SPINNY_TAG 5555
UIActivityIndicatorView *spinny = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinny.tag = SPINNY_TAG;
spinny.center = self.center;
[spinny startAnimating];
[self addSubview:spinny];
[spinny release];
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection
didReceiveData:(NSData *)incrementalData {
if (data==nil) {
data = [[NSMutableData alloc] initWithCapacity:2048];
}
[data appendData:incrementalData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection {
[connection release];
connection = nil;
UIView *spinny = [self viewWithTag:SPINNY_TAG];
[spinny removeFromSuperview];
if ([[self subviews] count] > 0) {
[[[self subviews] objectAtIndex:0] removeFromSuperview];
}
UIImage *image = [UIImage imageWithData:data];
[imageCache insertImage:image withSize:[data length] forKey:urlString];
UIImageView *imageView = [[[UIImageView alloc]
initWithImage:image] autorelease];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.autoresizingMask =
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self addSubview:imageView];
imageView.frame = self.bounds;
[imageView setNeedsLayout]; // is this necessary if superview gets setNeedsLayout?
[self setNeedsLayout];
[data release];
data = nil;
}
#end
If I wanna get picture from app source if url is empty , what code should I add ??
and here is more code from xyz.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.newsTable dequeueReusableCellWithIdentifier:
CellIdentifier];
if (cell == nil) {
//cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell = [self getCellContentView:CellIdentifier];
}
else{
AsyncImageView *oldImage = (AsyncImageView *)[cell.contentView viewWithTag:999];
[oldImage removeFromSuperview];
}
int index = [indexPath indexAtPosition: [indexPath length] - 1];
//Get Picture
CGRect frame;
frame.size.width=50; frame.size.height=50;
frame.origin.x=10; frame.origin.y=0;
AsyncImageView* asyncImage = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];
asyncImage.tag = 999;
NSString *string = [jsonPic objectAtIndex:index];
NSString *url=[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSURL *imageURL = [NSURL URLWithString:url];
if([string isEqualToString:#""]){
NSLog(#"Not found");
at here I don't know How can I get picture from source
AsyncImageView * NoImage = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];
NoImage.tag = 999;
NoImage.image = [UIImage imageNamed:#"bl-noImg.gif"];
[cell.contentView addSubview:NoImage];
}
else
{ NSLog(#"image URL %#",imageURL);
[asyncImage loadImageFromURL:imageURL];
[cell.contentView addSubview:asyncImage];
I can get picture from asyncImage
Please , Help me or guide me to do that. thank you
.
.
.
.
Now It's all done and here is my result code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.newsTable dequeueReusableCellWithIdentifier:
CellIdentifier];
if (cell == nil) {
//cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell = [self getCellContentView:CellIdentifier];
}
else{
AsyncImageView *oldImage = (AsyncImageView *)[cell.contentView viewWithTag:999];
[oldImage removeFromSuperview];
}
int index = [indexPath indexAtPosition: [indexPath length] - 1];
//Get Picture
CGRect frame;
frame.size.width=50; frame.size.height=50;
frame.origin.x=10; frame.origin.y=0;
AsyncImageView* asyncImage = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];
asyncImage.tag = 999;
NSString *string = [jsonPic objectAtIndex:index];
if([string isEqualToString:#""]){
//NSLog(#"Not found");
UIImageView * NoImg = [[[UIImageView alloc] initWithFrame:frame] autorelease];
NoImg.tag = 999;
[NoImg setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"bg-noImg" ofType:#"gif"]]];
[cell.contentView addSubview:NoImg];
}
else
{ //NSLog(#"image URL %#",imageURL);
NSString *url=[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSURL *imageURL = [NSURL URLWithString:url];
[asyncImage loadImageFromURL:imageURL];
[cell.contentView addSubview:asyncImage];
}
thank you everyone : )
If you are checking for empty url then you should check it before calling to loadImageFromURL and even before creating NSURL object. If it is not empty then you should create NSURL object and call loadImageFromURL method.
somewhere in your code... from where you are calling loadImageFromURL:
if(urlString !=nil || [urlString length]>0)
{
create NSURL object
now again check NSURL object whether its nil or not
we are checking it because if the urlString has incorrect url pattern then no
NSURLObject would be created, so if there is no NSURLObject then we should not call
your method.
if(NSURLObject !=nil)
{
call loadImageFromURL method and so on
}
else
{
//load some default image. which will convey no URL Found
}
}
else
{
//load some default image. which will convey no URL Found
}
Thanks,