Cell's String Text Not Being Updated When 'Reload Table" - iphone

My cells' string text (TDBadgedCell) is only updated when I edit data in the table's child table.
If I edit the same data from a different tab, then go back to this table, the string will not update until I relaunch the app.
I have this code as well:
- (void)viewWillAppear:(BOOL)animated
{
[self refreshFetchedResultsController];
[self.logTableView reloadData];
}
Edit:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
TDBadgedCell *cell = [[[TDBadgedCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)configureCell:(TDBadgedCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
cell.textLabel.textColor = [UIColor blackColor];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = [logArray objectAtIndex:indexPath.row];
cell.backgroundColor = [UIColor clearColor];
cell.imageView.image = [UIImage imageNamed:#"17-bar-chart.png"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM d, y"];
NSDate *date = nil;
NSDate *today = [NSDate date];
NSDate *thisWeek = [today dateByAddingTimeInterval: -604800.0];
NSDate *thisMonth = [today dateByAddingTimeInterval: -2629743.83];
if (indexPath.row == 0)
{
date = [NSDate date];
NSString *dateString = [dateFormatter stringFromDate:date];
cell.badgeString = dateString;
}
else if (indexPath.row == 1)
{
if ([[self.fetchedResultsController fetchedObjects]count] > 1)
{
self.session = [[self.fetchedResultsController fetchedObjects]objectAtIndex:1];
NSDate *date = self.session.timeStamp;
NSString *dateString = [dateFormatter stringFromDate:date];
cell.badgeString = dateString;
}
else
{
cell.badgeString = #"None";
}
}
else if (indexPath.row == 2)
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setPredicate: [NSPredicate predicateWithFormat:#"(timeStamp >= %#) AND (timeStamp <= %#)", thisWeek, today]];
[fetchRequest setEntity:[NSEntityDescription entityForName:#"Session" inManagedObjectContext:managedObjectContext]];
NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
NSLog(#"Fetch error: %#", error);
cell.badgeString = [NSString stringWithFormat:#"%i", [results count]];
[fetchRequest release];
}
else if (indexPath.row == 3)
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"(timeStamp >= %#) AND (timeStamp <= %#)", thisMonth, today]];
[fetchRequest setEntity:[NSEntityDescription entityForName:#"Session" inManagedObjectContext:managedObjectContext]];
NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
NSLog(#"Fetch error: %#", error);
cell.badgeString = [NSString stringWithFormat:#"%i", [results count]];
[fetchRequest release];
}
else if (indexPath.row == 4)
{
cell.badgeString = [NSString stringWithFormat:#"%i", [[self.fetchedResultsController fetchedObjects] count]];
NSLog(#"%i", [[self.fetchedResultsController fetchedObjects] count]);
}
UIImageView *myImageView = nil;
if (indexPath.row == 0 || indexPath.row == 1)
{
int myInt = cell.badgeString.length;
if (myInt > 11)
{
myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"silvercell7.png"]];
}
else if (myInt < 5)
{
myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"silvercell9.png"]];
}
else
{
myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"silvercell8.png"]];
}
}
else
{
myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"silvercell5.png"]];
}
[cell setBackgroundView:myImageView];
[myImageView release];
cell.badgeColor = [UIColor colorWithRed:24/255.0 green:83/255.0 blue:170/255.0 alpha:1.0];
[cell.badge setNeedsDisplay];
[dateFormatter release];
}

I think, you might be able to see the image for the newly added row. But not text Because you don't have support for that in your code.
In you code, you are always creating the new cell, Try with reusing the cell with below code.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableString *CellIdentifier = [[NSMutableString alloc] initWithCapacity:10]
[CellIdentifier appendFormat:#"Cell_%d_%d",indexPath.section,indexPath.row];
TDBadgedCell *cell = (TDBadgedCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
TDBadgedCell *cell = [[[TDBadgedCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}
[self configureCell:cell atIndexPath:indexPath];
return cell;
}

Related

App suddenly crashes on an NSLog of my NSMutableArray

I have a very strange problem. I've made an app, everything works ok.
But now it suddenly crashes on my NSMutableArray.
Here is a screenshot of the situation
A few days ago everything worked normal. Can it be that this comes because of the update of XCODE and IOS 7 or is it something else?
Can somebody help me? if you need more detailed information. Please ask.
EDIT
The array comes from a mutableCopy of my fetchRequest results.
NSArray *matches = [context executeFetchRequest:fetchRequest error:nil];
newsArray = [matches mutableCopy];
EDIT 2
-(void)fetchNews{
newsArray = [[NSMutableArray alloc]init];
RKManagedObjectStore *store = [[TerbremeDataModel sharedDataModel] objectStore];
NSManagedObjectContext *context = store.mainQueueManagedObjectContext;
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"News"];
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:#"new_id" ascending:NO];
fetchRequest.sortDescriptors = #[descriptor];
NSArray *matches = [context executeFetchRequest:fetchRequest error:nil];
newsArray = [matches mutableCopy];
[tableview reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"NewsCell";
NewsCell *cell = (NewsCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"NewsCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"tablecellbg.png"]];
cell.accessoryView = [[ UIImageView alloc ] initWithImage:[UIImage imageNamed:#"tableArrow.png" ]];
News *news = [newsArray objectAtIndex:indexPath.row];
NSLog(#"news is %#",news);
static NSDateFormatter *df;
static NSDateFormatter *df2;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
df2 = [[NSDateFormatter alloc] init];
[df2 setDateFormat:#"d MMMM yyyy"];
});
cell.lblText.font = [UIFont fontWithName:#"GillSans" size:15.0];
cell.lblDate.font = [UIFont fontWithName:#"GillSans" size:15.0];
cell.lblDate.textColor = [UIColor colorWithRed:(154/255.0) green:(202/255.0) blue:(0/255.0) alpha:100];
cell.lblText.text = news.new_title;
NSDate *date = [df dateFromString:news.new_datepublished];
cell.lblDate.text = [df2 stringFromDate:date];
return cell;
}
If you are using ARC I would assign the newsArray using the objective c facilities, i.e. the generated accessor method.
So it would be
self.newsArray = [[NSMutableArray alloc]init];

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;
}

Array goes empty in DidSelectRowAtIndexPath

I have in my coreDatabase an entity "Day". In a method I fetch the data from that entity and put it in a mutuableArray dayObjects. You can see the code over here.
NSManagedObjectContext *context = [RKManagedObjectStore defaultStore].persistentStoreManagedObjectContext;
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"Day"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:
#"p_date >= %# and p_date <= %#",dateString,dateString2];
[fetchRequest setPredicate:predicate];
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:#"p_id" ascending:YES];
fetchRequest.sortDescriptors = #[descriptor];
NSArray *matches = [context executeFetchRequest:fetchRequest error:nil];
NSLog(#"matches = %#",[matches valueForKey:#"p_date"]);
arrDateObjects = [matches mutableCopy];
In my cellForRow I do this
Day *objDay = [arrDateObjects objectAtIndex:indexPath.row-1];
Cell.titlelabel.text = day.p_from;
In my tableview the data is showed correctly. The problem is dat when I do the same thing in my DidSelectRowAtIndexPath. I always get a Null when I log day.p_from.
Can anybody help me ?
EDIT
My numberOfSections
(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
int sections = 0;
sections = 1;
return sections;
}
My numberOfRowsInSection
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int rows = 0;
rows = 8; //showing 7 days + 1 row for a little title
return rows;
}
My CellForRowAtIndexPath
static NSString *simpleTableIdentifier = #"OpeningCell";
OpeningCell *cell = (OpeningCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"OpeningCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if(indexPath.row == 0){
cell.lblDay.text = NSLocalizedString(#"lblDag", nil);
cell.lblFrom.text = NSLocalizedString(#"lblVan", nil);
cell.lblTill.text = NSLocalizedString(#"lblTot", nil);
}else{
Day *objDay = [arrDateObjects objectAtIndex:indexPath.row-1];
NSLog(#"Day object in cell from = %#",objDay.p_from);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"YYYY-MM-dd"];
NSDate *date = [dateFormat dateFromString:objDay.p_date];
NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init];
[dateFormat2 setDateFormat:#"dd/MM"];
NSString *dateString = [dateFormat2 stringFromDate:date];
NSLog(#"date: %#", dateString);
cell.lblShort.text = dateString;
cell.lblDay.text = [arrDays objectAtIndex:indexPath.row-1];
NSString *txtFrom = [objDay.p_from substringWithRange:NSMakeRange(0, 5)];
cell.lblFrom.text = txtFrom;
NSString *txtTill = [objDay.p_till substringWithRange:NSMakeRange(0, 5)];
cell.lblTill.text = txtTill;
}
return cell;
NSLog(#"matches = %#",[matches valueForKey:#"p_date"]);
arrDateObjects=[[NSMutableArray alloc]init];
[arrDateObjects addobject:[matches objectAtindex:indexpath.row-1]];
Instead of
NSLog(#"matches = %#",[matches valueForKey:#"p_date"]);
arrDateObjects = [matches mutableCopy];
//try
arrDateObjects = [NSMutableArray arrayWithArray:matches];
//instead of
arrDateObjects = [matches mutableCopy];

array returns null value ,arr = [[tempDict1 valueForKey:#"rates"] componentsSeparatedByString:#";"];

I am having a problem with displaying NSArray values in a UITableView. In my code I am getting nil value.
arr = [[tempDict1 valueForKey:#"rates"] componentsSeparatedByString:#";"];
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
values = [responseString JSONValue];
array = [[NSMutableArray alloc] init];
NSMutableArray *arrTitle = [[NSMutableArray alloc] init];
NSMutableArray *arrValues = [[NSMutableArray alloc] init];
array =[values valueForKey:#"rates"];
NSLog(#"array values:--> %#",array);
// NSLog(#"values:--> %#",values);
// NSLog(#"Particular values:--> %#",[[values valueForKey:#"rates"] valueForKey:#"AED"]);
tempDict1 = (NSMutableDictionary *)array;
NSArray *arr;// =[[NSArray alloc]init];
arr = [[tempDict1 valueForKey:#"rates"] componentsSeparatedByString:#";"];
NSLog(#"arr-->%#",arr);
NSString *subStar = #"=";
[arrTitle removeAllObjects];
[arrValues removeAllObjects];
for (int i=0; i<[arr count]-1; i++)
{
[arrTitle addObject:[[arr objectAtIndex:i] substringToIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])-1]];
[arrValues addObject:[[arr objectAtIndex:i] substringFromIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])]];
NSLog(#"arrTitle is:--> %#",arrTitle);
}
tempDict1 = (NSMutableDictionary*)[array objectAtIndex:0];
array = [values valueForKey:#"rates"];
NSLog(#"tempDict--%#",[tempDict1 objectForKey:#"AED"]);
[array retain];
[tbl_withData reloadData];
}
uitableview code is below
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"array-->%#",array);
return [array count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
intIndexPath = indexPath.row;
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.textLabel.font = [UIFont systemFontOfSize:8];
cell.textLabel.numberOfLines = 4;
}
// NSLog(#"data is like:--> %#",array);
// cell.textLabel.text= [NSString stringWithFormat:#"%#",[array objectAtIndex:intIndexPath]];
cell.textLabel.text =[array objectAtIndex:intIndexPath];
return cell;
}
Look through table view programming guide
https://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/AboutTableViewsiPhone/AboutTableViewsiPhone.html
You have to implement UITableView delegate methods in your class to fill table view with content.
Also see this:
https://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/CreateConfigureTableView/CreateConfigureTableView.html#//apple_ref/doc/uid/TP40007451-CH6-SW10
Here is code:
//this is your dictionary:
self.values = [[[NSMutableDictionary alloc] init] autorelease];
//filled it with values:
[self.values setObject:#"201" forKey:#"ams"];
[self.values setObject:#"500.50" forKey:#"hyd"];
[self.values setObject:#"200.10" forKey:#"guj"];
[self.values setObject:#"400" forKey:#"afgd"];
//now get an array of keys out of it. Can do it anywehe... For example in connectionDidFinishLoading method
self.keys = [[[NSArray alloc] initWithArray:[values allKeys]] autorelease];
Now cellForRoAtIndexPath method:
- (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.textLabel.adjustsFontSizeToFitWidth = YES;
cell.textLabel.font = [UIFont systemFontOfSize:8];
cell.textLabel.numberOfLines = 4;
}
NSString *currentKey = [self.keys objectAtIndex:indexPath.row];
NSString *currentValue = [self.values objectForKey:currentKey];
NSString *cellText = [NSString stringWithFormat:#"%#:%#", currentKey, currentValue];
cell.textLabel.text = cellText;
return cell;
}
It worked on my machine..

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.