Fetching data in background, but table view not updating - iphone

I want to switch to next view immediately using push view controller, so using below method to fetch data from web services. But this is not updating UITableView.
// vewDidLoad
[NSThread detachNewThreadSelector:#selector(setImage) toTarget:self withObject:nil];
-(void)setImage
{
if([type isEqualToString:#"Organisation"])
{
self.mGetDataDict = [MyEventApi members:self.mUserIdDict];
self.mRecievedDataDict = [self.mGetDataDict valueForKey:#"members"];
}
if([type isEqualToString:#"Individual"]){
self.mGetDataDict = [MyEventApi friends:self.mUserIdDict];
self.mRecievedDataDict = [self.mGetDataDict valueForKey:#"friends"];
}
if([self.mGetDataDict valueForKey:#"friends"] == [NSNull null])
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"alert" message:#"You have not added any friend yet." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
else
{
self.mFrndNameArr = [[NSMutableArray alloc]init];
self.mFrndImgArr = [[NSMutableArray alloc]init];
self.mFirstNameArr = [[NSMutableArray alloc]init];
self.mLastNameArr = [[NSMutableArray alloc]init];
self.mFrndIdArr = [[NSMutableArray alloc]init];
self.mFrndMSinceArr = [[NSMutableArray alloc]init];
self.mFrndDescArr = [[NSMutableArray alloc]init];
self.mFrndNameArr = [self.mRecievedDataDict valueForKey:#"username"];
self.mFrndImgArr = [self.mRecievedDataDict valueForKey:#"image"];
self.mFirstNameArr = [self.mRecievedDataDict valueForKey:#"firstName"];
self.mLastNameArr = [self.mRecievedDataDict valueForKey:#"lastName"];
self.mFrndIdArr = [self.mRecievedDataDict valueForKey:#"id"];
self.mFrndMSinceArr = [self.mRecievedDataDict valueForKey:#"memberSince"];
self.mFrndDescArr = [self.mRecievedDataDict valueForKey:#"description"];
[self.mFriendsTable reloadData];
}
}
Below is cellForRowAtIndexPath method.
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell;
cell = [self.mFriendsTable dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
else{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSString *imageUrlString = [NSString stringWithFormat:#"http://www.myevent.co/%#", [self.mFrndImgArr objectAtIndex:indexPath.row]];
[imageUrlString stringByReplacingOccurrencesOfString:#"/" withString:#""];
UILabel *lblEventName = [[UILabel alloc]initWithFrame:CGRectMake(92, 5, 200, 25)];
lblEventName.font = [UIFont fontWithName:#"Helvetica-Bold" size:14];
lblEventName.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:lblEventName];
if([copyArr count] >0)
{
lblEventName.text = [copyArr objectAtIndex:indexPath.row];
}
else{
lblEventName.text = [self.mFrndNameArr objectAtIndex:indexPath.row];
}
asyncImageView = [[AsyncImageView alloc]initWithFrame:CGRectMake(1, 3, 85, 54)];
[asyncImageView loadImageFromURL:[NSURL URLWithString:imageUrlString]];
[cell.contentView addSubview:asyncImageView];
cell.textLabel.backgroundColor = [UIColor colorWithRed:240.0/255.0 green:240.0/255.0 blue:240.0/255.0 alpha:1.0];
cell.contentView.backgroundColor = [UIColor colorWithRed:240.0/255.0 green:240.0/255.0 blue:240.0/255.0 alpha:1.0];
return cell;
}
The text data is fetched but images are not fetched until table scrolled. But if i use this way it shows the images also but switches to next view after all dat is fetched.
// vewDidLoad
[self setImage];
Please guide for above, is the way iam using threads wrong or any other way or method needs to be used here.

Since you are updating data in seperate thread ,You have to execute the reload on the main thread itself
instead of this
[self.mFriendsTable reloadData];
use this
[self.mFriendsTable performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:YES];

Related

UITableViewCell(s) with default image overwritten with other images upon scrolling

Oops,I am facing an issue with table view cells having no image,i.e. the cell with default image.Upon scrolling the default image disappears and some image from a cell is appearing on it.I have implemented the suggestion from Mr.Rckoenes here .Even then I was unable to fix the issue.Here is my implementation code for understanding:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ReminderClass *reminderToDisplay = [self.remindersArray objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
// Now create the cell to display the data
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellIdentifier] autorelease];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:kHelvetica size:17.0];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.backgroundColor = [UIColor clearColor];
}
......
if (Image != nil)
{
UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(240, 3, 70, 63)];
imageView.backgroundColor=[UIColor clearColor];
[imageView setImage:Image];
cell.accessoryView = imageView;
[imageView release];
}
else
{
UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(240, 3, 70, 63)];
imageView.backgroundColor=[UIColor clearColor];
UIImage *defaultImage = [UIImage imageNamed:kDefaultImage];
[imageView setImage:defaultImage];
cell.accessoryView = imageView;
[imageView release];
}
cell.textLabel.text = reminderDetailsString;
return cell;
}
Can any one please help me,thanks in advance :)
just set dequeueReusableCellWithIdentifier to nil and also reuseIdentifier to nil like bellow..
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
and
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
and also add your other code in this if (cell == nil) if condition..
UPDATE:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell%d%d",indexPath.section,indexPath.row];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:kHelvetica size:17.0];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.backgroundColor = [UIColor clearColor];
tableView.backgroundColor = [UIColor clearColor];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc]init]autorelease];
[dateFormat setDateFormat:kDateFormat];
NSDate *reminderDate = [dateFormat dateFromString:reminderToDisplay.Date];
[dateFormat setDateFormat:kMinDateFormat];
NSString *dateString = [dateFormat stringFromDate:reminderDate];
NSString *valueString = [NSString stringWithFormat:kNameEvent,reminderToDisplay.Name,reminderToDisplay.Event];
NSString *onString = [NSString stringWithFormat:kOn,dateString];
NSString *reminderDetailsString = [valueString stringByAppendingString:onString];
ABAddressBookRef addressbook = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressbook);
CFIndex numPeople = ABAddressBookGetPersonCount(addressbook);
for (int i=0; i < numPeople; i++)
{
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
NSString *firstName=(NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSString *lastName=(NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
NSMutableDictionary *contactsDictionary = [[[NSMutableDictionary alloc]init]autorelease];
if(firstName != nil && firstName != NULL)
{
[contactsDictionary setObject:firstName forKey:kFirstName];
CFRelease(firstName);
}
else
{
[contactsDictionary setObject:#"" forKey:kFirstName];
}
if(lastName != nil && lastName != NULL)
{
[contactsDictionary setObject:lastName forKey:kLastName];
CFRelease(lastName);
}
else
{
[contactsDictionary setObject:#"" forKey:kLastName];
}
//Get the first name and last name added to dict and combine it to form contact name
firstName = [[[NSString alloc]initWithString:[contactsDictionary objectForKey:kFirstName]]autorelease];
lastName = [NSString stringWithFormat:#" %#",[contactsDictionary objectForKey:kLastName]];
self.contactName = [firstName stringByAppendingString:lastName];
//Now check whether the contact name is same as your reminderToDisplay.Name
if([reminderToDisplay.Name isEqualToString:contactName] && ABPersonHasImageData(person))
{
CFDataRef imageData = ABPersonCopyImageData(person);
self.reminderImage = [UIImage imageWithData:(NSData *)imageData];
CFRelease(imageData);
}
}
CFRelease(allPeople);
CFRelease(addressbook);
if ([reminderToDisplay.reminderGroup isEqualToString:kFacebook])
{
NSString *imageName = [NSString stringWithFormat:kImageName,reminderToDisplay.Name];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *reminderString=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithString:imageName]];
self.reminderImage = [UIImage imageWithContentsOfFile:reminderString];
}
if (reminderImage != nil)
{
UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(240, 3, 70, 63)];
imageView.backgroundColor=[UIColor clearColor];
[imageView setImage:reminderImage];
cell.accessoryView = imageView;
[imageView release];
}
else
{
UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(240, 3, 70, 63)];
imageView.backgroundColor=[UIColor clearColor];
UIImage *defaultImage = [UIImage imageNamed:kDefaultImage];
[imageView setImage:defaultImage];
cell.accessoryView = imageView;
[imageView release];
}
cell.textLabel.text = reminderDetailsString;
}
return cell;
}

UITableview doubts

i am having an application which can share Notes to evernote,it works fine i can upload and download my Note to Evernote within the app,i have a Note title and Note subject,i uploaded the Notes to evernote viz UITableview controller.The Textlabel.text is the title for the note and detailtextlabel.text is the note subject.i only get the Notesubject correctly means ,if i have two notes in tableview with title,like this formate 1) title :firstitle ,notesubject :firstNotessubject 2)title :secondtitle ,notesubject :secondNotessubject,,then i press the upload button it uploads the notes to evernote,but the title remains firstitle only with notes,like this formate 1) title :firstitle ,notesubject :firstNotessubject 2)title :firsttitle ,notesubject :secondNotessubject.my code for uplode button is
-(IBAction)sendNoteEvernote:(id)sender{
NSMutableString *strtitle = [[NSMutableString alloc] initWithString:#""];
for (int t = 0; t<[appDelegate.indexArray count]; t++) {
NSString * aStringtitle = [[NSString alloc] initWithString:[appDelegate.indexArray objectAtIndex:t]] ;
note.title =aStringtitle;
}
NSMutableString *str = [[NSMutableString alloc] initWithString:#"NOTES:"];
for (int i = 0; i<[appDelegate.notesArray count]; i++) {
NSString * aString = [[NSString alloc] initWithString:[appDelegate.notesArray objectAtIndex:i]] ;
NSString * ENML= [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n<en-note>%#",aString];
ENML = [NSString stringWithFormat:#"%#%#", ENML, #"</en-note>"];
NSLog(#"%#", ENML);
// Adding the content & resources to the note
[note setContent:ENML];
// [note setTitle:aStringtitle];
// [note setResources:resources];
// Saving the note on the Evernote servers
// Simple error management
#try {
[[eversingleton sharedInstance] createNote:note];
_acteverbackup.hidden = YES;
_actimageeverbackup.hidden =YES;
}
#catch (EDAMUserException * e) {
_acteverbackup.hidden = YES;
_actimageeverbackup.hidden =YES;
NSString * errorMessage = [NSString stringWithFormat:#"Error saving note: error code %i", [e errorCode]];
proAlertView *alert = [[proAlertView alloc]initWithTitle:#"Evernote" message:errorMessage delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0] withStrokeColor:[UIColor colorWithHue:0.0 saturation:0.0 brightness:0.0 alpha:1.0]];
[alert show];
[alert release]; return;
}
in the above code appdelegate.indexarray is the title and appdelegate.notearray is the Subject..my UItableview code look like this.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return[appDelegate.notesArray count];
}
/*-(UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypesForRowWithIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellAccessoryCheckmark;
}*/
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = [indexPath row];
NSString *CellIdentifier;
CellIdentifier=[NSString stringWithFormat:#"cell %d",indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.detailTextLabel.numberOfLines = 0;
UIImageView* img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"bgCELL3#2X-1"]];
[cell setBackgroundView:img];
[img release];
count++;
}
NSMutableString *strr=[[NSMutableString alloc]initWithString:[appDelegate.indexArray objectAtIndex:indexPath.section]];
cell.textLabel.text =strr ;
cell.textLabel.text = [appDelegate.indexArray objectAtIndex:row];
cell.textLabel.font = [UIFont fontWithName:#"Georgia" size:14.0];
cell.textLabel.textColor = [UIColor brownColor];
//NSMutableString *notes=[[NSMutableString alloc]initWithString:[appDelegate.notesArray objectAtIndex:row]];
//cell.detailTextLabel.text =notes;
cell.detailTextLabel.font = [UIFont fontWithName:#"Georgia" size:14.0];
cell.detailTextLabel.textColor = [UIColor darkGrayColor];
cell.detailTextLabel.text = [appDelegate.notesArray objectAtIndex:row];
//textView.text=notes;
//[notes release];
cell.backgroundColor=[UIColor clearColor];
cell.accessoryType = UITableViewCellAccessoryNone;
return cell;
}
whats the error in my code,please help me to do this.
thanks in advance
Try changing the line:
NSMutableString *strr = [[NSMutableString alloc] initWithString:[appDelegate.indexArray objectAtIndex:indexPath.section]];
to:
NSMutableString *strr = [[NSMutableString alloc] initWithString:[appDelegate.indexArray objectAtIndex: row]];
Also get rid of the:
NSUInteger row = [indexPath row];
NSString *CellIdentifier;
CellIdentifier = [NSString stringWithFormat:#"cell %d",indexPath.row];
simply use:
CellIdentifier = #"noteCellIdentifier";
This doesn't have anything to do with your question but it's what cell reusing is all about.
EDIT:
This part of code also looks suspitious:
for (int t = 0; t<[appDelegate.indexArray count]; t++) {
NSString * aStringtitle = [[NSString alloc] initWithString:[appDelegate.indexArray objectAtIndex:t]] ;
note.title =aStringtitle;
}
It's not clear what you want to do but you'd probably want to move this to:
for (int i = 0; i<[appDelegate.notesArray count]; i++) {
NSString * aStringtitle = [[NSString alloc] initWithString:[appDelegate.indexArray objectAtIndex:i]]; //note: t changed to i
note.title =aStringtitle;
NSString * aString = [[NSString alloc] initWithString:[appDelegate.notesArray objectAtIndex:i]];
NSString * ENML= [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n<en-note>%#",aString];
ENML = [NSString stringWithFormat:#"%#%#", ENML, #"</en-note>"];
NSLog(#"%#", ENML);
//....

tableview refreshing while searching on iphone

I have a table view that shows 3 data side by side in table ,lets say A(name) , B(roll no) , C(id).
Now if user do search based on A's (search by name) (table get refreshed with name while searching only) value I want to either hide the content of B & C or they should show the correct value while search is on , not the old value which they got before searching.
I couldn't find the solution how to deal with remaining B & C.kindly suggest
here is my code
- (void) searchTableView
{
NSLog(#"search button is down %#",searchBar.text);
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
if(SearchQuery==1)
{
[searchArray addObjectsFromArray:[entityArray valueForKey:#"Name"]];
}
if(SearchQuery==2)
{
[searchArray addObjectsFromArray:[entityArray valueForKey:#"IC"]];
}
for (NSString *sTemp in searchArray)
{
NSLog(#"copyListOfItems in search -%#",copyListOfItems);//final array for names
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObject *object = (NSManagedObject *)[entityArray objectAtIndex:indexPath.row];
NSString *CellIdentifier = #"Cell";
int indicator = UITableViewCellAccessoryNone;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 50.0)] autorelease];//220
mainLabel.tag = MAINLABEL_TAG;
[mainLabel setFont:[UIFont fontWithName:#"Helvetica-Bold" size:18]];//Palatino-BoldItalic
mainLabel.textAlignment = UITextAlignmentLeft;
mainLabel.textColor = [UIColor blackColor];
secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(313.0, 9.0, 200.0, 25.0)] autorelease];//83
secondLabel.tag = SECONDLABEL_TAG;
smallSystemFontSize]]];
[secondLabel setFont:[UIFont fontWithName:#"Helvetica" size:18]];
secondLabel.textAlignment = UITextAlignmentLeft;
secondLabel.textColor = [UIColor blackColor];
[cell.contentView addSubview:secondLabel];
//// 3rd labl display
thirdLabel = [[[UILabel alloc] initWithFrame:CGRectMake(560.0, 9.0, 250.0, 25.0)] autorelease];//83
thirdLabel.tag = THIRDLABEL_TAG;
//thirdLabel.font = [UIFont systemFontOfSize:13.0];
[thirdLabel setFont:[UIFont fontWithName:#"Helvetica" size:18]];//Palatino-BoldItalic
thirdLabel.textAlignment = UITextAlignmentLeft;
thirdLabel.textColor = [UIColor blackColor];
[cell.contentView addSubview:thirdLabel];
}
if(searching)
{
NSLog(#" seacrh List in table view =%#",[copyListOfItems objectAtIndex:indexPath.row]);
// NSString *s=[object valueForKey:#"Name"];
NSLog(#"copyListOfItems length ---------%d",[copyListOfItems count]);
cell.textLabel.text =[copyListOfItems objectAtIndex:indexPath.row] ;
if(SearchQuery==2)
{
secondLabel.text=#"kk";// not working
secondLabel.alpha=1; // this is not working i cant upadate
}
}
else
{
if(self.entityName == #"Parent")
{
{
indicator = UITableViewCellAccessoryDisclosureIndicator;
CellIdentifier = #"CellWithDisclosure";
}
}
if(SearchQuery==2)
{
cell.textLabel.text =[object valueForKey:#"IC"] ;
secondLabel = (UILabel *)[cell.contentView viewWithTag:SECONDLABEL_TAG];
thirdLabel = (UILabel *)[cell.contentView viewWithTag:THIRDLABEL_TAG];
NSLog(#"sex is %# ",[object valueForKey:#"Name"]);
secondLabel.text=[object valueForKey:#"Name"] ;
secondLabel.alpha=0;
thirdLabel.text=[object valueForKey:#"roll"] ;
}

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

iphone nsurlconnect, tableview and activity indicator

i've a method that perform a connection to retreive some data and popolate a tableview.
This method works great.
Now i'm launching this method in viewDidLoad with
[NSThread detachNewThreadSelector:#selector(connTre)
toTarget:self
withObject:nil];
i've create this other function:
- (void)initSpinner {
av = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(195.0, 8.0, 30.0, 30.0) ] autorelease];
av.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
[av hidesWhenStopped];
[self.view addSubview:av];
}
(i've initialite this in viewDidLoad)
- (void)spinBegin {
[av startAnimating];
}
- (void)spinEnd {
[av stopAnimating];
}
where's the better place to start and stop my activityindicatorview?
I've try to start with
[self performSelectorOnMainThread:#selector(spinBegin)
withObject:nil
waitUntilDone:false];
Here's my pretty standard code for table datasource:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [listaOggetti count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSDictionary *dictionary = [listaOggetti objectAtIndex:section];
NSArray *array = [dictionary objectForKey:#"Elementi"];
return [array count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 30;
}
-(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];
cell.selectionStyle = UITableViewCellStyleValue1 ;
}
NSInteger sectionRows = [tableView numberOfRowsInSection:[indexPath section]];
NSInteger row = [indexPath row];
// Configure the cell.
NSDictionary *dictionary = [listaOggetti objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"Elementi"];
NSString *cellValue = [array objectAtIndex:indexPath.row];
if (row == 0){
cell.textLabel.text = cellValue;
cell.textAlignment = UITextAlignmentCenter;
cell.backgroundColor = [UIColor redColor];
cell.font = [UIFont systemFontOfSize:13];
cell.selectionStyle = UITableViewCellStyleValue1 ;
} else {
cell.textLabel.text = cellValue;
cell.textAlignment = UITextAlignmentCenter;
cell.backgroundColor = [UIColor whiteColor];
cell.selectionStyle = UITableViewCellStyleValue1 ;
}
return cell;
}
this is the method for get my data:
- (void)connTre {
NSThread *spinThread=[[NSThread alloc] initWithTarget:self
selector:#selector(startSpinning) object:nil];
[spinThread start];
NSError *error;
NSURLResponse *response;
NSData *dataReply;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: #"myloginurl"]];
[request setHTTPMethod: #"GET"];
dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//message tre soglie ok
path = #"my_url_for_getting_data";
url = [NSURL URLWithString:path];
NSError *errors;
htmlString = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&errors];
NSString *regexString = #"(?:\r\n|[\n\v\f\r\302\205\\p{Zl}\\p{Zp}])";
NSString *reg2 =#".+class=\"dettaglioSoglie.*";
NSString *reg3 =#"</table>";
NSString*reg4=#"<td><b>(.+) </b></td><td>(.+) </td><td>(.+) </td><td>(.+) </td>";
NSString *replaceWithString = #"$1";
NSString *replaceWithString1 = #"Effettuato $2";
NSString *replaceWithString2 = #"Rimanente $3";
NSString *replaceWithString3 = #"Totale $4";
if(htmlString){
NSArray *linesArray = [htmlString componentsSeparatedByRegex:regexString];
for(NSString *lineString in linesArray) {
if(lineString ==[lineString stringByMatching:reg2]) { print = YES;}
if (print == YES) {
if(lineString ==[lineString stringByMatching:reg4]) {
replace = [lineString stringByReplacingOccurrencesOfRegex:reg4 withString:replaceWithString];
replace1 = [lineString stringByReplacingOccurrencesOfRegex:reg4 withString:replaceWithString1];
replace2 = [lineString stringByReplacingOccurrencesOfRegex:reg4 withString:replaceWithString2];
replace3 = [lineString stringByReplacingOccurrencesOfRegex:reg4 withString:replaceWithString3];
//NSLog(#"%#\n%#\n%#\n%#\n",replace, replace1, replace2, replace3);
//sectionz = [NSMutableArray arrayWithObjects: replace, nil];
//NSMutableArray *voice = [NSMutableArray arrayWithObjects: replace, replace1, replace2, replace3, nil];
NSMutableArray *voice = [NSMutableArray arrayWithObjects: replace, replace1, replace2, replace3, nil];
NSDictionary *detVoice = [NSDictionary dictionaryWithObject:voice forKey:#"Elementi"];
[listaOggetti addObject:detVoice];
NSLog(#"%#", listaOggetti);
}
//NSLog(#"%#",listaDettaglioOggetti);
}
if (lineString ==[lineString stringByMatching:reg3]) { print = NO;}
}
} else {
NSLog(#"Error reading file '%#'", htmlString);
}
[av stopAnimating];
[spinThread release];
}
and this is how i've configure my spinning:
- (void)startSpinning {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
av = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(195.0, 8.0, 30.0, 30.0) ] autorelease];
av.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
[av hidesWhenStopped];
[self.view addSubview:av];
[av startAnimating];
[pool release];
}
with no lucky: jobs were perform, i see with nslog my data, av start and stop but data were not populated in my table (i don't see empty table, i don't see any table).
if i don't perform my animation i get my right table with data.
Thank's.
I don't know this is the correct way or not but this works fine for me.
-(void) yourFunctionThatPopulatesTableView
{
NSThread *spinThread=[[NSThread alloc] initWithTarget:self selector:#selector(startSpinner) object:nil];
[spinThread start];
//Populate TableView
//Last Line of he function
[av stopAnimating];
[spinThread release];
}
-(void)startSpinner
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
CGRect frame = CGRectMake(195.0, 8.0, 30.0, 30.0);
av = [[UIActivityIndicatorView alloc] initWithFrame:frame];
av.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
[av hidesWhenStopped];
[self.view addSubview:av];
[av startAnimating];
[pool release];
}
Any Function called by thread should have a NSAutoReleasePool as per documentation.