Table view error - ios

The table view is not working when loading.It is giving an error.Here is the error.
NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 1
beyond bounds [0 .. 0]'
Here is my code.
- (void)viewDidLoad
{
[super viewDidLoad];
uiButtonArray =[[NSMutableArray alloc]init];
[SharedPreferenceUtil saveBoolValueInUserDefaults:YES forKey:#"viewupdate"];
indexval = 0;
if (isNotification)
{
isNotification = NO;
[UIApplication sharedApplication].applicationIconBadgeNumber=0;
//[[UIApplication sharedApplication]cancelAllLocalNotifications];
}
[self getRemarks];
[self updateUI];
// Do any additional setup after loading the view.
}
-(void) viewDidLayoutSubviews
{
[remarksTable setFrame:CGRectMake(5, 190, [[UIScreen mainScreen]bounds].size.width-20, [[UIScreen mainScreen]bounds].size.height-180)];
[Calendarscroll setFrame:CGRectMake(0,90,320, 59)];
[Calendarscroll setBackgroundColor:[UIColor whiteColor]];
Calendarscroll.contentSize =CGSizeMake(1500, 59);
[self.view layoutIfNeeded];
}
-(void)fillcalendar
{
buttonIndex=0;
for (UIButton *btn in uiButtonArray )
{
[btn removeFromSuperview];
}
[uiButtonArray removeAllObjects];
globalDate=currentDate;
// this is the placeholder for the calendar
// setting up the month title
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MMMM yyyy"];
[monthLabel setText:[df stringFromDate:currentDate]];
NSDateComponents *components = [calendar components:NHWunits fromDate:currentDate];
// change for the first day
[components setDay:1];
// update the component
components = [calendar components:NHWunits fromDate:[calendar dateFromComponents:components]];
[components setDay:-[components weekday]+2];
int lessDay = [components day];
int month = [components month];
int year = [components year];
// extracting components from date
NSDateComponents *components3 = [calendar components:NHWunits fromDate:[NSDate date]];
int currentDateInteger=[components3 day];
monthInteger=[components3 month];
yearInteger=[components3 year];
CGFloat orgx=0,orgy=1.0f;
int m=month;
for (int week=0; week<6 && month==m; week++)
{
for (int d=0; d<7; d++)
{
[components setDay:lessDay];
int d =[[calendar components:NHWunits fromDate:[calendar dateFromComponents:components]] day];
m =[[calendar components:NHWunits fromDate:[calendar dateFromComponents:components]] month];
int y =[[calendar components:NHWunits fromDate:[calendar dateFromComponents:components]] year];
NSString *daysdate = [NSString stringWithFormat:#"%d-%d-%d",d,m,y];
NSDateFormatter *nwd =[[NSDateFormatter alloc]init];
[nwd setDateFormat:#"dd-MM-yyyy"];
NSDate *notdays =[nwd dateFromString:daysdate];
[nwd setDateFormat:#"EEE"];
NSString *WDays =[nwd stringFromDate:notdays];
UILabel *Weekdays =[self createLbl:WDays orgx:orgx orgy:orgy];
UIButton *button = [self createBtn:d orgx:orgx orgy:orgy Date:currentDate];
if (d==defaultDateInteger && defaultMonthInteger==m)
{
// globalButton=button;
}
NSString *isSunday =[NSString stringWithFormat:#"%d-%d-%d",d,m,y];
NSDate *date = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"d-M-yyyy"];
NSString *cdate = [df stringFromDate:date];
NSLog(#"CURRENT DATE: %# \n %#", isSunday,cdate);
//Circle the Today's Date
if ([isSunday isEqualToString:cdate]) {
[button setBackgroundColor:[UIColor lightGrayColor]];
// [button.titleLabel setTextColor:[UIColor whiteColor]];
}
[Calendarscroll addSubview:button];
[Calendarscroll addSubview:Weekdays];
button.tag=buttonIndex;
[uiButtonArray addObject:button];
// [DayArray addObject:Weekdays];
buttonIndex++;
orgx+=46;
lessDay++;
}
}
}
- (UIButton*) createBtn:(int)day orgx:(CGFloat)orgx orgy:(CGFloat)orgy Date:(NSDate*)caldate
{
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
NSDateFormatter *cMonth = [[NSDateFormatter alloc] init];
[cMonth setDateFormat:#"MMMM yyyy"];
NSDate *date = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"dd-MM-yyyy"];
NSDateFormatter *dff = [[NSDateFormatter alloc]init];
[dff setDateFormat:#"d"];
NSDateFormatter *days =[[NSDateFormatter alloc]init];
[days setDateFormat:#"EEE"];
NSString *cdate1 = [dff stringFromDate:date];
NSLog(#"The single date is: %#",cdate1);
NSString *cdate = [df stringFromDate:date];
NSLog(#"df is: %#",cdate);
NSString *cdays =[days stringFromDate:date];
NSLog(#"The days are: %#",cdays);
[button setBackgroundColor:[UIColor colorWithRed:0.52 green:0.5 blue:0.12 alpha:0.8]];
button.titleEdgeInsets = UIEdgeInsetsMake(-14.0, -16.0, 0.0, 0.0);
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTitle:[NSString stringWithFormat:#"%d", day] forState:UIControlStateNormal];
[button.titleLabel setFont:[UIFont systemFontOfSize:16.0f]];
button.frame=CGRectMake(orgx, 28, 35, 30);
return button;
}
-(UILabel*) createLbl:(NSString*)Days orgx:(CGFloat)orgx orgy:(CGFloat)orgy
{
UILabel *Weekdays =[[UILabel alloc]initWithFrame:CGRectMake(orgx, 5, 35, 20)];
NSDateFormatter *cMonth = [[NSDateFormatter alloc] init];
[cMonth setDateFormat:#"MMMM yyyy"];
NSDate *Ndate = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"dd-MM-yyyy"];
NSDateFormatter *days =[[NSDateFormatter alloc]init];
[days setDateFormat:#"EEE"];
NSString *cdate = [df stringFromDate:Ndate];
NSLog(#"df is: %#",cdate);
NSString *cdays =[days stringFromDate:Ndate];
NSLog(#"The days are: %#",cdays);
[Weekdays setBackgroundColor:[UIColor colorWithRed:0.52 green:0.5 blue:0.12 alpha:0.8]];
//Weekdays.titleEdgeInsets = UIEdgeInsetsMake(-14.0, -16.0, 0.0, 0.0);
[Weekdays setTextColor:[UIColor blackColor]];
[Weekdays setText:[NSString stringWithFormat:#"%#", Days]];
[Weekdays setFont:[UIFont systemFontOfSize:16.0f]];
return Weekdays;
}
-(void)CreateSection
{
sectionsData =[[NSMutableArray alloc]init];
for (int i=0; i<collectHW.count; i++)
{
/* [sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"Title: %#",[[collectHW objectAtIndex:i] valueForKey:#"name"]],[NSString stringWithFormat:#"DUE DATE: %#",[[collectHW objectAtIndex:i] valueForKey:#"deadlinedate"]],[NSString stringWithFormat:#"DESCRIPTION: %#",[[collectHW objectAtIndex:i] valueForKey:#"description"]],[NSString stringWithFormat:#"Tap to download attachment."],#"hasAttachment",nil]];
// [Sectiondata addObject:sectionarray];
NSLog(#"The description is: %#",sectionsData);*/
//for (int i =0; i<newsArray.count; i++)
if ([[[collectHW objectAtIndex:i] valueForKey:#"path"]stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:BLANK_STRING]].length!=0)
{
[sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"DESCRIPTION: %#",[[collectHW objectAtIndex:i] valueForKey:#"description"]],[NSString stringWithFormat:#"Tap to download attachment."],#"hasAttachment",nil]];
}
else
{
[sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"DESCRIPTION: %#",[[collectHW objectAtIndex:i] valueForKey:#"description"]], nil]];
}
/* if ([[[collectHW objectAtIndex:i] valueForKey:#"path"]stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:BLANK_STRING]].length!=0)
{
if ([[[collectHW objectAtIndex:i] valueForKey:#"name"]stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:BLANK_STRING]].length!=0)
{
if ([[[collectHW objectAtIndex:i] valueForKey:#"deadlinedate"]stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:BLANK_STRING]].length!=0)
{
if ([[[collectHW objectAtIndex:i] valueForKey:#"description"]stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:BLANK_STRING]].length!=0)
{
[sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"Title: %#",[[collectHW objectAtIndex:i] valueForKey:#"name"]],[NSString stringWithFormat:#"DUE DATE: %#",[[collectHW objectAtIndex:i] valueForKey:#"deadlinedate"]],[NSString stringWithFormat:#"DESCRIPTION: %#",[[collectHW objectAtIndex:i] valueForKey:#"description"]],[NSString stringWithFormat:#"Tap to download attachment."],#"hasAttachment",nil]];
NSLog(#"The description is: %#",sectionsData);
}else
{
[sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"Title: %#",[[collectHW objectAtIndex:i] valueForKey:#"name"]],[NSString stringWithFormat:#"DUE DATE: %#",[[collectHW objectAtIndex:i] valueForKey:#"deadlinedate"]],[NSString stringWithFormat:#"Tap to download attachment."],#"hasAttachment",nil]];
}
}else{////deadlinedate........
if ([[[collectHW objectAtIndex:i] valueForKey:#"description"]stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:BLANK_STRING]].length!=0)
{
[sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"Title: %#",[[collectHW objectAtIndex:i] valueForKey:#"name"]],[NSString stringWithFormat:#"DESCRIPTION: %#",[[collectHW objectAtIndex:i] valueForKey:#"description"]],[NSString stringWithFormat:#"Tap to download attachment."],#"hasAttachment",nil]];
NSLog(#"The description is: %#",sectionsData);
}else
{
[sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"Title: %#",[[collectHW objectAtIndex:i] valueForKey:#"name"]],[NSString stringWithFormat:#"Tap to download attachment."],#"hasAttachment",nil]];
}
}
}else
{//////name........
if ([[[collectHW objectAtIndex:i] valueForKey:#"deadlinedate"]stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:BLANK_STRING]].length!=0)
{
if ([[[collectHW objectAtIndex:i] valueForKey:#"description"]stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:BLANK_STRING]].length!=0)
{
[sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"DUE DATE: %#",[[collectHW objectAtIndex:i] valueForKey:#"deadlinedate"]],[NSString stringWithFormat:#"DESCRIPTION: %#",[[collectHW objectAtIndex:i] valueForKey:#"description"]],[NSString stringWithFormat:#"Tap to download attachment."],#"hasAttachment",nil]];
NSLog(#"The description is: %#",sectionsData);
}else
{
[sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"DUE DATE: %#",[[collectHW objectAtIndex:i] valueForKey:#"deadlinedate"]],[NSString stringWithFormat:#"Tap to download attachment."],#"hasAttachment",nil]];
}
}else{////deadlinedate........
if ([[[collectHW objectAtIndex:i] valueForKey:#"description"]stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:BLANK_STRING]].length!=0)
{
[sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"DESCRIPTION: %#",[[collectHW objectAtIndex:i] valueForKey:#"description"]],[NSString stringWithFormat:#"Tap to download attachment."],#"hasAttachment",nil]];
NSLog(#"The description is: %#",sectionsData);
}else
{
[sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"Tap to download attachment."],#"hasAttachment",nil]];
}
}
}
}else
{/////////path......
if ([[[collectHW objectAtIndex:i] valueForKey:#"name"]stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:BLANK_STRING]].length!=0)
{
if ([[[collectHW objectAtIndex:i] valueForKey:#"deadlinedate"]stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:BLANK_STRING]].length!=0)
{
if ([[[collectHW objectAtIndex:i] valueForKey:#"description"]stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:BLANK_STRING]].length!=0)
{
[sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"Title: %#",[[collectHW objectAtIndex:i] valueForKey:#"name"]],[NSString stringWithFormat:#"DUE DATE: %#",[[collectHW objectAtIndex:i] valueForKey:#"deadlinedate"]],[NSString stringWithFormat:#"DESCRIPTION: %#",[[collectHW objectAtIndex:i] valueForKey:#"description"]],nil]];
// NSLog(#"The description is: %#",sectionsData);
}else
{
[sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"Title: %#",[[collectHW objectAtIndex:i] valueForKey:#"name"]],[NSString stringWithFormat:#"DUE DATE: %#",[[collectHW objectAtIndex:i] valueForKey:#"deadlinedate"]],nil]];
}
}else{////deadlinedate........
if ([[[collectHW objectAtIndex:i] valueForKey:#"description"]stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:BLANK_STRING]].length!=0)
{
[sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"Title: %#",[[collectHW objectAtIndex:i] valueForKey:#"name"]],[NSString stringWithFormat:#"DESCRIPTION: %#",[[collectHW objectAtIndex:i] valueForKey:#"description"]],nil]];
// NSLog(#"The description is: %#",sectionsData);
}else
{
[sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"Title: %#",[[collectHW objectAtIndex:i] valueForKey:#"name"]],nil]];
}
}
}else
{//////name........
if ([[[collectHW objectAtIndex:i] valueForKey:#"deadlinedate"]stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:BLANK_STRING]].length!=0)
{
if ([[[collectHW objectAtIndex:i] valueForKey:#"description"]stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:BLANK_STRING]].length!=0)
{
[sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"DUE DATE: %#",[[collectHW objectAtIndex:i] valueForKey:#"deadlinedate"]],[NSString stringWithFormat:#"DESCRIPTION: %#",[[collectHW objectAtIndex:i] valueForKey:#"description"]],nil]];
// NSLog(#"The description is: %#",sectionsData);
}else
{
[sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"DUE DATE: %#",[[collectHW objectAtIndex:i] valueForKey:#"deadlinedate"]],nil]];
}
}else{////deadlinedate........
if ([[[collectHW objectAtIndex:i] valueForKey:#"description"]stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:BLANK_STRING]].length!=0)
{
[sectionsData addObject:[[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:#"DESCRIPTION: %#",[[collectHW objectAtIndex:i] valueForKey:#"description"]],nil]];
// NSLog(#"The description is: %#",sectionsData);
}else
{
[self showDropDownViewWithmessage:#"No homework is yet to display." title:#"Message" inView:self.view];
}
}
}
}*/
NSLog(#"The new data is: %#",sectionsData);
}
UIColor *sectionsColor = [UIColor colorWithRed:36.0f/255.0f green:158.0f/255.0f blue:110.0f/255.0f alpha:1.0f];
UIColor *sectionTitleColor = [UIColor whiteColor];
UIFont *sectionTitleFont = [UIFont fontWithName:#"Futura" size:24.0f];
EMAccordionSection *section;
// emTV.closedSectionIcon=[UIImage imageNamed:#"icon_down.png"];
// emTV.openedSectionIcon=[UIImage imageNamed:#"icon_up.png"];
for (int i = 0 ; i<collectHW.count; i++)
{
section = [[EMAccordionSection alloc] init];
[section setBackgroundColor:sectionsColor];
[section setItems:[sectionsData objectAtIndex:i]];
[section setTitle:[NSString stringWithFormat:#"%#(%#)",[[collectHW objectAtIndex:i] valueForKey:#"subjectname"],[[collectHW objectAtIndex:i] valueForKey:#"assignmenttype"]]];
[section setTitleFont:sectionTitleFont];
[section setTitleColor:sectionTitleColor];
[emTV addAccordionSection:section];
}
NSLog(#"The Section is: %#",section.title);
[remarksTable reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"emCell"];
NSMutableArray *items = [sectionsData objectAtIndex:indexPath.section];
UILabel *titleLbl = [[UILabel alloc] initWithFrame:CGRectMake(5.0f,0.0f,220.0f, 40.0f)];
[titleLbl setFont:[UIFont boldSystemFontOfSize:14.0f]];
[titleLbl setText:[items objectAtIndex:indexPath.row]];
[titleLbl setBackgroundColor:[UIColor clearColor]];
[titleLbl setTextColor:[UIColor blackColor]];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [[items objectAtIndex:indexPath.row] sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height+10, 40.0f);
[titleLbl setFrame:CGRectMake(30, titleLbl.frame.origin.y, 280.0f, height)];
titleLbl.numberOfLines=30;
[[cell contentView] addSubview:titleLbl];
[cell setBackgroundColor:[UIColor clearColor]];
return cell;
}
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//TAHomeworksTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"homeworkCell"];
NSMutableArray *items = [sectionsData objectAtIndex:indexPath.section];
NSString *text = [items objectAtIndex:[indexPath row]];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height+15, 40.0f);
return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
NSString *text = [NSString stringWithFormat:#"%#(%#)",[[collectHW objectAtIndex:section] valueForKey:#"subjectname"],[[collectHW objectAtIndex:section] valueForKey:#"assignmenttype"]];
NSLog(#"The text is: %#",text);
CGSize constraint = CGSizeMake(250.0f - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont boldSystemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height+35, 40.0f);
return height;
}
- (UIColor *)colorWithHexString:(NSString *)str_HEX alpha:(CGFloat)alpha_range{
int red = 0;
int green = 0;
int blue = 0;
sscanf([str_HEX UTF8String], "#%02X%02X%02X", &red, &green, &blue);
return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha_range];
}
-(void)updateUI
{
emTV = [[EMAccordionTableViewController alloc] initWithTable:remarksTable];
[emTV setDelegate:self];
[self addCustomBackButtonWithNaviBarColor:[self colorWithHexString:#"#c3b395" alpha:1.0f]];
//[self addCustomBackButton];
if (IS_IOS7)
{
[remarksTable setSeparatorInset:UIEdgeInsetsZero];
}
[self addCustomBackButtonWithNaviBarColor:[self colorWithHexString:#"#006666" alpha:1.0f]];
NSMutableArray *menuindex = (NSMutableArray *)[SharedPreferenceUtil getNSObject:#"menuindexarray"];
[self addCutomTitleToCustomNavigationBar:[NSString stringWithFormat:#"%#",[(NSMutableArray *)[SharedPreferenceUtil getNSObject:#"appnamearray"]objectAtIndex:[[menuindex objectAtIndex:[(NSString *)[SharedPreferenceUtil getNSObject:#"selmenuitem"]integerValue]]integerValue]]]];
currentDate=[NSDate date];
globalDate=currentDate;
calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
//today = [[NSDate alloc] initWithTimeIntervalSinceNow:1];
NSDateComponents *components = [calendar components:NHWunits fromDate:currentDate];
defaultDateInteger=components.day;
[self fillcalendar];
// [self getdate];
// [self dateSelectedInPickerView];
[self getRemarks];
}
-(void)getRemarks
{
if ([self connected])
{
[self showLoadingViewWithMessage:#"Loading..."];
[[DPSAppService sharedInstance] getDataFromURL:[self getURL] responseBlock:^(NSDictionary *response)
{
if (response)
{
NSLog(#"%#",response);
homewokArray = [response valueForKey:#"studentassignment"];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd-MM-yyyy"];
NSDate *CurrentDate =[NSDate date];
NSString *cDate =[df stringFromDate:CurrentDate];
NSLog(#" current Month date is: %#",cDate);
collectHW =[[NSMutableArray alloc]init];
for (int i=0; i<homewokArray.count; i++)
{
NSLog(#"New data is: %#",[[homewokArray objectAtIndex:i]valueForKey:#"date"]);
if ([cDate isEqualToString:[[homewokArray objectAtIndex:i]valueForKey:#"date"]])
{
[collectHW addObject:[homewokArray objectAtIndex:i]];
}
else
{
NSLog(#"No Homework today");
}
}
NSLog(#"Current data of homework is: %#",collectHW);
if (homewokArray.count==0)
{
[self showDropDownViewWithmessage:#"No homework is yet to display." title:#"Message" inView:self.view];
}else
{
[self CreateSection];
// [self showHomework];
}
}
else
{
[self showDropDownViewWithmessage:SERVER_ERROR title:ERROR inView:self.view];
}
[self hideLoadingViewWithSuccessMessage:LOGIN_SUCCESS];
[self addBottomView];
}];
}
else
{
}
}
-(NSString *)getURL
{
return [NSString stringWithFormat:#"%#%#%#classid=%#&academciyearid=%#&sectionid=%#",[SharedPreferenceUtil getNSObject:#"baseerpurl"],URL,STUDENT_HOMEWORK,[[SharedPreferenceUtil getNSObject:STUDENT_DATA_JSON ]valueForKey:#"classid"],[[SharedPreferenceUtil getNSObject:STUDENT_DATA_JSON ]valueForKey:#"academciyearid"],[[SharedPreferenceUtil getNSObject:STUDENT_DATA_JSON ]valueForKey:#"sectionid"]];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

Add exceptional breakpoint and see how many objects are there in Array and from which index an object being taken out from that array,by doing this you will be able to find out and sort out the problem :)

You always have to return the correct value in numberOfRowsInSection method. GENERALLY, that value is the count of an array. If this is also your case then please debug your flow and check for inconsistencies. Whenever the count of the array is altered or changed, the tableview should be reloaded.

Related

Objective-C NSMutableArray process 15 items at a time

I have an NSMutableArray like so:
NSMutableArray *value = [productionSchedule valueForKeyPath:#"Value"];
When populated this NSMutableArray could have 900 rows or just 8 or 12, There is no way of knowing, so what I am trying to do is process the first 15 rows and then the next 15 rows and so on till its done.
I am able to to process the first 15 rows with this:
for(int i = 0; i < 15; i++)
{
}
But then how would I process the next 15 from NSMutableArray?
Here is the full loop in question:
for(int i = 0; i< [prodSchedSortedKeys count]; i++)
{
NSMutableArray *valueArray = [[NSMutableArray alloc]init];
NSArray *baseLineFinishArray = [value objectAtIndex:i];
for(int j = 0 ;j< [newTaskData count]; j++)
{
ProductionCellData *pModel = [[ProductionCellData alloc]init];
if([[[baseLineFinishArray objectAtIndex:j] valueForKey:#"task"] isEqual: #"Closing Date"])
{
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"yyyy-MM-dd h:mm:ss a"];
pModel.baseLineStart = [self SetSpecialDateFormat:[dateFormatter dateFromString:[[baseLineFinishArray objectAtIndex:j] valueForKey:#"baselinefinish"]]WithOption:0];
pModel.taskItem = [[baseLineFinishArray objectAtIndex:j] valueForKey:#"task"];
[valueArray addObject: pModel];
}
else if([[[baseLineFinishArray objectAtIndex:j] valueForKey:#"task"] isEqual: #"Days To Closing"])
{
[pModel setCellColor:[self SetCellColor:[[[baseLineFinishArray objectAtIndex:j] valueForKey:#"baselinefinish"] intValue]]];
pModel.baseLineStart = [[baseLineFinishArray objectAtIndex:j] valueForKey:#"baselinefinish"];
pModel.taskItem = [[baseLineFinishArray objectAtIndex:j] valueForKey:#"task"];
[valueArray addObject: pModel];
}
else if([[[baseLineFinishArray objectAtIndex:j] valueForKey:#"task"] isEqual: #"Schedule Variance"])
{
[pModel setCellColor:[self SetCellColor:[[[baseLineFinishArray objectAtIndex:j] valueForKey:#"baselinefinish"] intValue]]];
pModel.baseLineStart = [[baseLineFinishArray objectAtIndex:j] valueForKey:#"baselinefinish"];
pModel.taskItem = [[baseLineFinishArray objectAtIndex:j] valueForKey:#"task"];
[valueArray addObject: pModel];
}
else if([[[baseLineFinishArray objectAtIndex:j] valueForKey:#"task"] isEqual: #"Days Of Construction"])
{
[pModel setCellColor:[self SetCellColor:[[[baseLineFinishArray objectAtIndex:j] valueForKey:#"baselinefinish"] intValue]]];
pModel.baseLineStart = [[baseLineFinishArray objectAtIndex:j] valueForKey:#"baselinefinish"];
pModel.taskItem = [[baseLineFinishArray objectAtIndex:j] valueForKey:#"task"];
[valueArray addObject: pModel];
}
else if([[[baseLineFinishArray objectAtIndex:j] valueForKey:#"task"] isEqual: #"NOTES"])
{
pModel.baseLineStart = [[baseLineFinishArray objectAtIndex:j] valueForKey:#"baselinefinish"];
pModel.taskItem = [[baseLineFinishArray objectAtIndex:j] valueForKey:#"task"];
[valueArray addObject: pModel];
}
else if([[[baseLineFinishArray objectAtIndex:j] valueForKey:#"task"] isEqual: #"PDI To Close"])
{
[pModel setCellColor:[self SetCellColor:[[[baseLineFinishArray objectAtIndex:j] valueForKey:#"baselinefinish"] intValue]]];
pModel.baseLineStart = [[baseLineFinishArray objectAtIndex:j] valueForKey:#"baselinefinish"];
pModel.taskItem = [[baseLineFinishArray objectAtIndex:j] valueForKey:#"task"];
[valueArray addObject: pModel];
}
else
{
[pModel setTextCol:[self SetTextColor:[baseLineFinishArray objectAtIndex:j]]];
[pModel setCellColor:[self SetCellColor:[self DateDifference:[baseLineFinishArray objectAtIndex:j]]]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd h:mm:ss a"];
pModel.baseLineStart = [self SetSpecialDateFormat:[dateFormatter dateFromString:[[baseLineFinishArray objectAtIndex:j] valueForKey:#"baselinefinish"]]WithOption:0];
pModel.actualFinish = [self SetSpecialDateFormat:[dateFormatter dateFromString:[[baseLineFinishArray objectAtIndex:j] valueForKey:#"actualenddate"]]WithOption:0];
pModel.taskItem = [[baseLineFinishArray objectAtIndex:j] valueForKey:#"task"];
[valueArray addObject:pModel];
[dateFormatter release]; dateFormatter=nil;
}
[pModel release];
pModel = nil;
}
[finalProductionSchedule setObject:valueArray forKey:[prodSchedSortedKeys objectAtIndex:i]];
[valueArray release];
valueArray = nil;
}
[prodSchedSortedKeys count] could be over 900, or just 12, its the count of number of rows of data.
After doing some debugging, I have determined that this is slowing everything down and taking up memory:
- (NSString *)SetSpecialDateFormat:(NSString *)date
{
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:#"dd-MM-yyyy"];
NSString *theDate = date;
NSArray *array = [theDate componentsSeparatedByString:#" "];
dateFormat = nil;
return [array objectAtIndex:0];
}

Dynamic expandable and collapsed table view cells?

I developed expandable and collapsed table view for dynamic data comes from the server. I'm displaying state names in header view successfully, but I can't displaying child data that is districts related to state names.
I followed Link for this http://www.iostute.com/2015/04/expandable-and-collapsable-tableview.html
My data is
_response = #{#"Response":#{#"status":#"SUCCESS",#"error_code":#"0",#"message":#"SUCCESS",#"Array":#[
#{#"state_id":#"0",#"state_name":#"null",#"district_id":#"0",#"district_name":#"null"},
#{#"state_id":#"01",#"state_name":#"State1",#"district_id":#"001",#"district_name":#"State1District1"},
#{#"state_id":#"02",#"state_name":#"State2",#"district_id":#"004",#"district_name":#"State2District1"},
#{#"state_id":#"02",#"state_name":#"State2",#"district_id":#"005",#"district_name":#"State3District1"},
#{#"state_id":#"01",#"state_name":#"State1",#"district_id":#"002",#"district_name":#"State1District2"},
#{#"state_id":#"01",#"state_name":#"State1",#"district_id":#"003",#"district_name":#"State1District3"},
#{#"state_id":#"03",#"state_name":#"State3",#"district_id":#"006",#"district_name":#"State3District1"},
#{#"state_id":#"04",#"state_name":#"State4",#"district_id":#"008",#"district_name":#"State4District1"},
#{#"state_id":#"04",#"state_name":#"State4",#"district_id":#"009",#"district_name":#"State4District2"},
#{#"state_id":#"04",#"state_name":#"State4",#"district_id":#"010",#"district_name":#"State4District3"},
#{#"state_id":#"05",#"state_name":#"State5",#"district_id":#"011",#"district_name":#"State5District1"},
#{#"state_id":#"05",#"state_name":#"State5",#"district_id":#"012",#"district_name":#"State5District2"},
#{#"state_id":#"03",#"state_name":#"State3",#"district_id":#"007",#"district_name":#"State3District2"}]}, #"count":#"6"};
My code is
if ([[[_response objectForKey:#"Response"] objectForKey:#"status"] isEqualToString:#"SUCCESS"] && (!(_integer == 0))) {
_stateID = [[NSMutableArray alloc] init];
_stateName = [[NSMutableArray alloc] init];
_districtID = [[NSMutableArray alloc] init];
_districtName = [[NSMutableArray alloc] init];
_stateIdStateNameDic = [[NSMutableDictionary alloc]init];
//Add arrays to array to remove null values dynamically
NSArray *arr = [[NSArray alloc]initWithObjects:_stateID, _stateName, _districtID, _districtName, nil];
for (int i=0; i<_integer; i++) {
[_stateID addObject:[[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"state_id"]];
[_stateName addObject:[[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"state_name"]];
[_districtID addObject:[[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"district_id"]];
[_districtName addObject:[[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"district_name"]];
//Remove null values
for (int j=0; j<arr.count; j++) {
for (NSMutableArray *ar in arr) {
if ([[ar objectAtIndex:i] isKindOfClass:[NSNull class]] || [[ar objectAtIndex:i] isEqualToString:#"null"] || [[ar objectAtIndex:i] isEqualToString:#"0"]) {
[ar addObject:#""];
[ar removeObjectAtIndex:i];
}
}
}
}
//Add arrays to mutable array to remove empty objects
NSMutableArray *marr = [[NSMutableArray alloc]initWithObjects:_stateID, _stateName, _districtID, _districtName, nil];
//Remove empty objects from all arrays
for (int j=0; j<marr.count; j++) {
for (int i=0; i<[[marr objectAtIndex:j] count]; i++) {
if ([[[marr objectAtIndex:j] objectAtIndex:i] isEqualToString:#""]) {
[[marr objectAtIndex:j] removeObjectAtIndex:i];
}
}
}
//Remove duplicates from state names array
_stateName = [_stateName valueForKeyPath:#"#distinctUnionOfObjects.self"];
NSString *districtName = #"";
NSString * superater = #"&&";
_mdic = [[NSMutableDictionary alloc]init];
for (int j=0; j<_stateName.count; j++) {
for (int i=0; i<_integer; i++) {
if ([[_stateName objectAtIndex:j] isEqualToString:[[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"state_name"]]) {
//Remove district name if empty or null
if ([districtName isEqualToString:#""] || [districtName isEqual:[NSNull null]]) {
districtName = [[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"district_name"];
if ([districtName isEqual:[NSNull null]] || [districtName isEqualToString:#"null"]) {
districtName = #"";
}
} else {
//Add all districts with superater &&
districtName = [districtName stringByAppendingString:[NSString stringWithFormat:#"%#%#", superater, [[[[_response objectForKey:#"Response"] objectForKey:#"Array"] objectAtIndex:i] objectForKey:#"district_name"]]];
}
}
}
//Create district names dictionary with state name keys
[_mdic setValue:districtName forKey:[_stateName objectAtIndex:j]];
districtName = #"";
}
NSLog(#"_mdic %#", _mdic);
_arrayForBool=[[NSMutableArray alloc]init];
//Save bool value " NO " based on sectionTitleArray count.
for (int i=0; i<[_stateName count]; i++) {
[_arrayForBool addObject:[NSNumber numberWithBool:NO]];
}
dispatch_async(dispatch_get_main_queue(), ^{
[_availableOrdersTableView reloadData];
});
} else {
}
// TableView delegates
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [_mdic count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Number of rows in each section
if ([[_arrayForBool objectAtIndex:section] boolValue]) {
NSLog(#"%#", [_stateName objectAtIndex:section]);
NSLog(#"%#", _mdic);
NSArray *mdicKeys = [_mdic allKeys];
for (int i=0; i<_mdic.count; i++) {
if ([[mdicKeys objectAtIndex:i] isEqualToString:[_stateName objectAtIndex:section]]) {
NSString *str = [_mdic objectForKey:[_stateName objectAtIndex:section]];
NSLog(#"%#", str);
_subDistrictArr = [str componentsSeparatedByString:#"&&"];
}
}
NSLog(#"_subDistrictIDArr %#", _subDistrictArr);
return _subDistrictArr.count;
} else {
return 0;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//Create cell
static NSString *cellid=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellid];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellid];
}
BOOL manyCells = [[_arrayForBool objectAtIndex:indexPath.section] boolValue];
/********** If the section supposed to be closed *******************/
if(!manyCells)
{
cell.backgroundColor=[UIColor clearColor];
cell.textLabel.text=#"";
}
/********** If the section supposed to be Opened *******************/
else {
cell.textLabel.text=[_subDistrictArr objectAtIndex:indexPath.row];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
cell.textLabel.font=[UIFont systemFontOfSize:20.0f];
} else {
cell.textLabel.font=[UIFont systemFontOfSize:15.0f];
}
cell.backgroundColor=[UIColor whiteColor];
cell.selectionStyle=UITableViewCellSelectionStyleNone ;
}
cell.textLabel.textColor=[UIColor blackColor];
/********** Add a custom Separator with cell *******************/
UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(15, 48, _availableOrdersTableView.frame.size.width-15, 1)];
separatorLineView.backgroundColor = [UIColor blackColor];
[cell.contentView addSubview:separatorLineView];
return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *sectionView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, _availableOrdersTableView.frame.size.width, 50)];
sectionView.backgroundColor = [UIColor clearColor];
sectionView.tag=section;
UILabel *viewLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, _availableOrdersTableView.frame.size.width, sectionView.frame.size.height)];
viewLabel.backgroundColor=[UIColor clearColor];
viewLabel.textColor=[UIColor blackColor];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
viewLabel.font=[UIFont systemFontOfSize:25];
} else {
viewLabel.font=[UIFont systemFontOfSize:15];
}
viewLabel.text=[NSString stringWithFormat:#"%#", [_stateName objectAtIndex:section]];
_stateIDString = [_stateID objectAtIndex:section];
NSLog(#"stateIDString %#", _stateIDString);
[sectionView addSubview:viewLabel];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(sectionView.frame.size.width-45, (sectionView.frame.size.height-25)/2, 18, 17)];
imgView.tag = section;
imgView.image = [UIImage imageNamed:#"DA"];
[sectionView addSubview:imgView];
} else {
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(sectionView.frame.size.width-35, (sectionView.frame.size.height-25)/2, 18, 17)];
imgView.tag = section;
imgView.image = [UIImage imageNamed:#"DA"];
[sectionView addSubview:imgView];
}
/********** Add a custom Separator with Section view *******************/
UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(0, sectionView.frame.size.height, _availableOrdersTableView.frame.size.width, 1)];
separatorLineView.backgroundColor = [UIColor blackColor];
[sectionView addSubview:separatorLineView];
/********** Add UITapGestureRecognizer to SectionView **************/
UITapGestureRecognizer *headerTapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(sectionHeaderTapped:)];
[sectionView addGestureRecognizer:headerTapped];
return sectionView;
}
- (void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:gestureRecognizer.view.tag];
// _gestureInteger = gestureRecognizer.view.tag;
if (indexPath.row == 0) {
BOOL collapsed = [[_arrayForBool objectAtIndex:indexPath.section] boolValue];
for (int i=0; i<[_stateName count]; i++) {
if (indexPath.section==i) {
[_arrayForBool replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:!collapsed]];
}
}
[_availableOrdersTableView reloadSections:[NSIndexSet indexSetWithIndex:gestureRecognizer.view.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
// [_availableOrdersTableView reloadData];
}
}
I have two solution for this
(1) initially you put numberofrow for any section is zero and after click on any section you can add row for for clicked section.
(2) number of section will be one and you need to use two cell "cellwithheaderonly" and "cellwithheaderandsubpart" initially you will use "cellwithheaderonly" and when user will click on any cell you need to use "cellwithheaderandsubpart"
You can take reference from following URL
Expanding and Collapsing table view cells in ios
https://www.anexinet.com/blog/expandable-collapsible-uitableview-sections/
You have to maintain an array given below : -
lat arr = [[“name”:”firstRow” , “subRowArray”:[1,2,3,4]],[“name”:”secondRow” , “subRowArray”:[1,2,3,4]],[“name”:”thirdRow” , “subRowArray”:[1,2,3,4]]]
then expand and collapse according to your array .
if would you like to use library then go for expendable Tableview

Search bar not showing proper results

In my custom cell there are three labels: name, date and time.
When I search from namearray it shows proper filtered results, but my date and time label values remain unchanged, it always shows the values of my first and second record's date and time detail.
Code:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if(isFiltered)
{
return [arrsearchresult count];
}
return [arrfullname count];
}
// tableView delegate methods
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
AppoinmentTableViewCell *cell = (AppoinmentTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AppoinmentTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.btnCall.tag = indexPath.row;
cell.btnMail.tag = indexPath.row;
cell.btnSms.tag = indexPath.row;
cell.btnCreatePlan.tag = indexPath.row;
cell.btnAppointment.tag = indexPath.row;
cell.btnStatus.tag=indexPath.row;
}
cell.clipsToBounds = YES;
if ([strCheckVC isEqualToString:#"OpenLead"])
{
cell.lblFullname.text = [arrfullname objectAtIndex:indexPath.row];
[self databaseOpen];
NSString *query_user=[ NSString stringWithFormat:#"Select * from lead_status where row_lead_id = %# and lead_followup_datetime != ' ' order by rowid desc limit 1",[arrRowid objectAtIndex:indexPath.row]];
NSArray *rowids = [[NSArray alloc]init];
rowids =[[database executeQuery:query_user]mutableCopy];
NSLog(#"%#",rowids);
[database close];
if (rowids.count > 0 )
{
NSString *dateString = [[rowids valueForKey:#"lead_followup_datetime"]objectAtIndex:0];
NSArray *components = [dateString componentsSeparatedByString:#" "];
NSString *date = components[0];
NSString *time = components[1];
// date convert
NSString *dateStr = [NSString stringWithFormat:#"%#",date];
NSString *timestr = [NSString stringWithFormat:#"%#",time];
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"HH:mm:ss"];
NSDate *date11 = [dateFormat dateFromString:timestr];
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"hh:mm a"];
NSString *depResult = [df stringFromDate:date11];
cell.lblTime.text = depResult;
dateStr = [NSString stringWithFormat:#"%#",date];
// Convert string to date object
dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-mm-dd"];
NSDate *viewdt = [dateFormat dateFromString:dateStr];
//date11 = [dateFormat dateFromString:dateStr];
NSLog(#"%#",date);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date22 = [dateFormatter dateFromString:dateStr];
[dateFormatter setDateFormat:#"dd MMM yyyy"];
NSString *dateWithNewFormat = [dateFormatter stringFromDate:date22];
NSLog(#"dateWithNewFormat: %#", dateWithNewFormat);
// df = [[NSDateFormatter alloc]init];
// [df setDateFormat:#"dd MMM yyyy"];
// depResult = [df stringFromDate:viewdt];
//
cell.lblDate.text = dateWithNewFormat;
}
else
{
// date convert
NSString *dateStr = [NSString stringWithFormat:#"%#",[appointmenttime objectAtIndex:indexPath.row]];
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"HH:mm:ss"];
NSDate *date = [dateFormat dateFromString:dateStr];
NSLog(#"%#",date);
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"hh:mm a"];
NSString *depResult = [df stringFromDate:date];
cell.lblTime.text = depResult;
dateStr = [NSString stringWithFormat:#"%#",[arrappointment_date objectAtIndex:indexPath.row]];
// Convert string to date object
dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-mm-dd"];
date = [dateFormat dateFromString:dateStr];
NSLog(#"%#",date);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date22 = [dateFormatter dateFromString:dateStr];
[dateFormatter setDateFormat:#"dd MMM yyyy"];
NSString *dateWithNewFormat = [dateFormatter stringFromDate:date22];
NSLog(#"dateWithNewFormat: %#", dateWithNewFormat);
// df = [[NSDateFormatter alloc]init];
// [df setDateFormat:#"dd MMM yyyy"];
// depResult = [df stringFromDate:date];
//
cell.lblDate.text = dateWithNewFormat;
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if ([[arremail objectAtIndex:indexPath.row] isEqual:[NSNull null]] || [[arremail objectAtIndex:indexPath.row] isEqualToString:#"<null>"] || [[arremail objectAtIndex:indexPath.row] isEqualToString:#""] )
{
cell.btnMail.hidden = NO;
}
NSUInteger hours_passed = [[arrhours_passed objectAtIndex:indexPath.row] integerValue];
if (hours_passed <= 72)
{
cell.colorView.backgroundColor = [UIColor whiteColor];
}
else if (hours_passed <= 144)
{
cell.colorView.backgroundColor = [UIColor colorWithRed:219.0/255.0 green:157.0/255.0 blue:157.0/255.0 alpha:1.0];
cell.lblDate.textColor = [UIColor whiteColor];
cell.lblTime.textColor = [UIColor whiteColor];
cell.lblFullname.textColor = [UIColor whiteColor];
}
else if (hours_passed <= 216)
{
cell.colorView.backgroundColor = [UIColor colorWithRed:202.0/255.0 green:114.0/255.0 blue:114.0/255.0 alpha:1.0];
cell.lblDate.textColor = [UIColor whiteColor];
cell.lblTime.textColor = [UIColor whiteColor];
cell.lblFullname.textColor = [UIColor whiteColor];
}
else if (hours_passed <= 288)
{
cell.colorView.backgroundColor = [UIColor colorWithRed:189.0/255.0 green:78.0/255.0 blue:78.0/255.0 alpha:1.0];
cell.lblDate.textColor = [UIColor whiteColor];
cell.lblTime.textColor = [UIColor whiteColor];
cell.lblFullname.textColor = [UIColor whiteColor];
}
[self databaseOpen];
NSString *str = [NSString stringWithFormat:#"Select * from lead_followup where rowid=%#",[arrRowid objectAtIndex:indexPath.row]];
NSMutableArray *arr = [[NSMutableArray alloc]init];
arr = [[database executeQuery:str]mutableCopy];
NSLog(#"arr data %#",arr);
[database close];
NSString *strsms;
if (arr.count != 0)
{
strsms = [NSString stringWithFormat:#"%#",[[arr valueForKey:#"followed_by_sms"]objectAtIndex:0]];
if ([strsms isEqualToString:#"0"])
{
if (hours_passed <= 72)
{
[cell.btnSms setImage:[UIImage imageNamed:#"Chatgray"] forState:UIControlStateNormal];
}
else if (hours_passed > 72)
{
//white
[cell.btnSms setImage:[UIImage imageNamed:#"chatwhite"] forState:UIControlStateNormal];
}
}
/*else
{
// green icon
[cell.btnSms setImage:[UIImage imageNamed:#"Chatgreen"] forState:UIControlStateNormal];
}*/
NSString *strCall = [NSString stringWithFormat:#"%#",[[arr valueForKey:#"followed_by_call"]objectAtIndex:0]];
NSLog(#"%#",strCall);
if ([strCall isEqualToString:#"0"])
{
if (hours_passed <= 72)
{
//blackCallGray
[cell.btnCall setImage:[UIImage imageNamed:#"CallGray"] forState:UIControlStateNormal];
}
else if (hours_passed > 72)
{
[cell.btnCall setImage:[UIImage imageNamed:#"CallWhite"] forState:UIControlStateNormal];
}
}
else
{
[cell.btnCall setImage:[UIImage imageNamed:#"CallGreen"] forState:UIControlStateNormal];
// green icon
}
NSString *strmail = [NSString stringWithFormat:#"%#",[[arr valueForKey:#"followed_by_mail"]objectAtIndex:0]];
NSLog(#"%#",strmail);
if ([strmail isEqualToString:#"0"])
{
if (hours_passed <= 72)
{
[cell.btnMail setImage:[UIImage imageNamed:#"Mailgray"] forState:UIControlStateNormal];
}
else if (hours_passed > 72)
{
[cell.btnMail setImage:[UIImage imageNamed:#"MailWhite"] forState:UIControlStateNormal];
//white
}
}
/*else
{
[cell.btnMail setImage:[UIImage imageNamed:#"MailGreen"] forState:UIControlStateNormal];
// green icon
}*/
}
[cell.btnCall addTarget:self
action:#selector(callDo:) forControlEvents:UIControlEventTouchDown];
[cell.btnSms addTarget:self
action:#selector(smsDo:) forControlEvents:UIControlEventTouchDown];
[cell.btnMail addTarget:self
action:#selector(mailDo:) forControlEvents:UIControlEventTouchDown];
[cell.btnStatus addTarget:self
action:#selector(Status:) forControlEvents:UIControlEventTouchDown];
[cell.btnAppointment addTarget:self
action:#selector(AddappointmentId:) forControlEvents:UIControlEventTouchDown];
[cell.btnCreatePlan addTarget:self
action:#selector(CreatePlan:) forControlEvents:UIControlEventTouchDown];
if(self.btnSearchByName.selected==YES)
{
if(isFiltered)
{
cell.lblFullname.text = [arrsearchresult objectAtIndex:indexPath.row];
/*cell.lblDate.text = [arrsearchresult objectAtIndex:indexPath.row];
cell.lblTime.text = [arrsearchresult objectAtIndex:indexPath.row];*/
}
}
else
{
if(isFiltered)
{
//cell.lblFullname.text = [arrsearchresult objectAtIndex:indexPath.row];
cell.lblDate.text = [arrsearchresult objectAtIndex:indexPath.row];
//cell.lblTime.text = [arrsearchresult objectAtIndex:indexPath.row];
}
}
}
else
{
cell.lblFullname.text = [arrfullname objectAtIndex:indexPath.row];
cell.btnSms.hidden = YES;
cell.btnCall.hidden = YES;
cell.btnMail.hidden = YES;
cell.colorView.hidden =YES;
// cell.lblTime.text = [appointmenttime objectAtIndex:indexPath.row];
//cell.lblDate.text = [arrappointment_date objectAtIndex:indexPath.row];
NSString *dateStr = [NSString stringWithFormat:#"%#",[appointmenttime objectAtIndex:indexPath.row]];
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"HH:mm:ss"];
NSDate *date = [dateFormat dateFromString:dateStr];
NSLog(#"%#",date);
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"hh:mm a"];
NSString *depResult = [df stringFromDate:date];
cell.lblTime.text = depResult;
dateStr = [NSString stringWithFormat:#"%#",[arrappointment_date objectAtIndex:indexPath.row]];
// Convert string to date object
dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-mm-dd"];
date = [dateFormat dateFromString:dateStr];
NSLog(#"%#",date);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date22 = [dateFormatter dateFromString:dateStr];
[dateFormatter setDateFormat:#"dd MMM yyyy"];
NSString *dateWithNewFormat = [dateFormatter stringFromDate:date22];
NSLog(#"dateWithNewFormat: %#", dateWithNewFormat);
// df = [[NSDateFormatter alloc]init];
// [df setDateFormat:#"dd MMM yyyy"];
// depResult = [df stringFromDate:date];
//
cell.lblDate.text = dateWithNewFormat;
}
/* UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor clearColor];
[cell setSelectedBackgroundView:bgColorView];*/
if(self.btnSearchByName.selected==YES)
{
if(isFiltered)
{
cell.lblFullname.text = [arrsearchresult objectAtIndex:indexPath.row];
/*cell.lblDate.text = [arrsearchresult objectAtIndex:indexPath.row];
cell.lblTime.text = [arrsearchresult objectAtIndex:indexPath.row];*/
}
}
else
{
if(isFiltered)
{
//cell.lblFullname.text = [arrsearchresult objectAtIndex:indexPath.row];
cell.lblDate.text = [arrsearchresult objectAtIndex:indexPath.row];
//cell.lblTime.text = [arrsearchresult objectAtIndex:indexPath.row];
}
}
return cell;
}
- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if ([strCheckVC isEqualToString:#"OpenLead"])
{
if(self.btnSearchByName.selected==YES)
{
if(searchText.length==0)
{
isFiltered=NO;
}
else
{
isFiltered=YES;
arrsearchresult=[[NSMutableArray alloc]init];
for ( NSString * str in arrfullname)
{
NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location != NSNotFound)
{
[arrsearchresult addObject:str];
}
}
}
}
else
{
if(searchText.length==0)
{
isFiltered=NO;
}
else
{
isFiltered=YES;
arrsearchresult=[[NSMutableArray alloc]init];
for ( NSString * str in arrleadCreatedDate)
{
NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location != NSNotFound)
{
[arrsearchresult addObject:str];
}
}
}
}
}
else
{
if(self.btnSearchByName.selected==YES)
{
if(searchText.length==0)
{
isFiltered=NO;
}
else
{
isFiltered=YES;
arrsearchresult=[[NSMutableArray alloc]init];
for ( NSString * str in arrfullname)
{
NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location != NSNotFound)
{
[arrsearchresult addObject:str];
}
}
}
}
else
{
if(searchText.length==0)
{
isFiltered=NO;
}
else
{
isFiltered=YES;
arrsearchresult=[[NSMutableArray alloc]init];
NSString *searchString = searchBar.text;
for ( NSString * str in arrdatetime)
{
/*NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location != NSNotFound)
{
[arrsearchresult addObject:str];
}*/
NSComparisonResult result = [str compare:searchString options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchString length])];
if (result == NSOrderedSame) {
[arrsearchresult addObject:str];
}
}
}
}
}
[self.tblAppoinment reloadData];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
[self.tblAppoinment resignFirstResponder];
}

UIPickerView Empty

My issue is only with my picker "proPicker." The weird thing is, the objects are still in the array, as the text in my textfield changes even though the picker shows up blank....
I believe I have followed all of the steps to populate the picker, and 9 out of 10 times the picker shows the correct information, but sometimes it just shows up blank..
Here is my code:
.h:
//
// EditDebateViewController.h
//
//
// Created by Jacob Klapper on 10/17/13.
//
//
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#interface EditDebateViewController : UITableViewController <UITextFieldDelegate, UIPickerViewDelegate,UIActionSheetDelegate>
#property UIDatePicker *pickerView;
#property (weak, nonatomic) IBOutlet UITextField *topic;
#property (weak, nonatomic) IBOutlet UITextField *pro;
#property (weak, nonatomic) IBOutlet UITextField *con;
#property (weak, nonatomic) IBOutlet UITextField *pVotes;
#property (weak, nonatomic) IBOutlet UITextField *cVotes;
#property (weak, nonatomic) IBOutlet UITextField *abs;
#property (weak, nonatomic) IBOutlet UITextField *date;
#property NSMutableArray *pChoices;
#property NSMutableArray *pStrings;
#property NSMutableArray *cChoices;
#property NSMutableArray *cStrings;
#property NSMutableArray *proTest;
#property UIPickerView *proPicker;
#property PFObject *obj;
#end
.m:
//
// EditDebateViewController.m
//
//
// Created by Jacob Klapper on 10/17/13.
//
//
#import "EditDebateViewController.h"
#interface EditDebateViewController ()
#end
#implementation EditDebateViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
//self.date = [[UIDatePicker alloc]init];
self.date.delegate = self;
self.pro.delegate = self;
self.con.delegate = self;
self.pVotes.delegate = self;
self.cVotes.delegate = self;
self.abs.delegate = self;
self.topic.delegate = self;
self.pickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 322, 0, 0)];
self.pickerView.datePickerMode = UIDatePickerModeDate;
self.pickerView.hidden = true;
self.pickerView.date = [NSDate date];
[self.pickerView addTarget:self
action:#selector(updateLabel:)
forControlEvents:UIControlEventValueChanged];
//[self.view addSubview:pickerToolbar];
[self.tableView addSubview:self.pickerView];
//self.pickerView.del
self.date.inputView = self.pickerView;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
//[df setLocale:enUSPOSIXLocale];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setDateFormat:#"MMM dd, yyyy "];
self.proPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 322, 0, 0)];
self.proPicker.hidden = true;
self.proPicker.delegate = self;
[self.tableView addSubview:self.proPicker];
self.pro.inputView = self.proPicker;
self.pStrings = [[NSMutableArray alloc]init];
self.cStrings = [[NSMutableArray alloc]init];
self.pChoices = [[NSMutableArray alloc]initWithArray:[self.obj objectForKey:#"PR"]];
self.cChoices = [[NSMutableArray alloc]init];
self.proTest = [[NSMutableArray alloc]init];
//self.pChoices = [self.obj objectForKey:#"PR"];
//self.cChoices = [self.obj objectForKey:#"CR"];
NSLog(#"Choices Now: %#", self.pChoices);
NSLog(#"Choices Count: %lu", (unsigned long)[self.pChoices count]);
for (PFUser *us in self.pChoices) {
//NSLog(#"Hi");
//PFUser *user = [self.pChoices objectAtIndex:i];
[us fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) {
//[self.pChoices addObject:object];
//NSString *name = [NSString stringWithFormat:#"%# %#", [object objectForKey:#"firstName"], [object objectForKey:#"lastName"]];
//NSLog(name);
//[self.proTest addObject:object];
//NSLog(#"The value before pStrings is: %#", name);
//[self.pStrings addObject:name];
//NSLog(#"This is spot: %#", [self.pStrings objectAtIndex:i]);
[self.proTest addObject:object];
NSString *name = [NSString stringWithFormat:#"%# %#", [object objectForKey:#"firstName"], [object objectForKey:#"lastName"]];
[self.pStrings addObject:name];
NSLog(#"Pro Test: %#", self.proTest);
NSLog(#"Pro Strings: %#", self.pStrings);
NSLog(#"User: %#", us);
NSLog(#"Object: %#", object);
}];
}
NSLog(#"Strings: %#", self.pStrings);
NSLog(#"Pro Test: %lu", (unsigned long)[self.proTest count]);
//NSLog(#"%#", self.pStrings);
self.topic.text = [self.obj objectForKey:#"Topic"];
self.date.text = [df stringFromDate:[self.obj objectForKey:#"Date"]];
NSLog(#"Hi Test");
if([[NSString stringWithFormat:#"%#", [self.obj objectForKey:#"proVotes"] ] isEqualToString:#"0"])
{
NSLog(#"ITS NULL");
self.pVotes.text = #"";
}
//self.pVotes.text = [NSString stringWithFormat:#"%#", [self.obj objectForKey:#"proVotes"] ];
else
{
self.pVotes.text = [NSString stringWithFormat:#"%#", [self.obj objectForKey:#"proVotes"] ];
}
if([[NSString stringWithFormat:#"%#", [self.obj objectForKey:#"conVotes"] ] isEqualToString:#"0"])
{
self.cVotes.text = #"";
}
else
{
self.cVotes.text = [NSString stringWithFormat:#"%#", [self.obj objectForKey:#"conVotes"] ];
}
if([[NSString stringWithFormat:#"%#", [self.obj objectForKey:#"Abstentions"] ] isEqualToString:#"0"])
{
self.abs.text = #"";
}
else
{
self.abs.text = [NSString stringWithFormat:#"%#", [self.obj objectForKey:#"Abstentions"]];
}
/*
NSLog(#"Here");
NSLog(#"%#", proU);
self.pro.text = [NSString stringWithFormat:#"%# %#", [proU objectForKey:#"firstName"], [proU objectForKey:#"lastName"]];
PFUser *conU = [self.obj objectForKey:#"Con"];
//self.con.text = [NSString stringWithFormat:#"%# %#", [conU objectForKey:#"firstName"], [conU objectForKey:#"lastName"]];
*/
PFUser *proU = [self.obj objectForKey:#"Pro"];
[proU fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) {
self.pro.text = [NSString stringWithFormat:#"%# %#", [object objectForKey:#"firstName"], [object objectForKey:#"lastName"]];
}];
PFUser *conU = [self.obj objectForKey:#"Con"];
[conU fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) {
self.con.text = [NSString stringWithFormat:#"%# %#", [object objectForKey:#"firstName"], [object objectForKey:#"lastName"]];
}];
[self.pickerView setDate:[self.obj objectForKey:#"Date"]];
[self.proPicker reloadAllComponents];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewDidAppear:(BOOL)animated
{
[self.proPicker reloadAllComponents];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
/*
#pragma mark - Navigation
// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)backcustom:(UIBarButtonItem *)sender {
[self.navigationController popViewControllerAnimated:YES];
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
//[aTextField resignFirstResponder];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
//[df setLocale:enUSPOSIXLocale];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setDateFormat:#"MMM dd, yyyy "];
if(textField == self.topic)
{
NSLog(#"Topic");
}
if(textField == self.date)
{
self.pickerView.hidden = false;
self.date.text = [df stringFromDate:self.pickerView.date];
}
if(textField == self.pro)
{
self.proPicker.hidden = false;
//self.pro.text =
NSInteger rowSelectionKg = [self.proPicker selectedRowInComponent:0]; //get currrent row of picker for first column
NSString *tempKg = [self.pStrings objectAtIndex:rowSelectionKg]; //use row as index to get value in corresponding array of choices in picker
self.pro.text = tempKg;
}
//pickerViewPopup = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
return YES;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (pickerView == self.proPicker) {
self.pro.text = [self.pStrings objectAtIndex:row];
}
else
{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
//[df setLocale:enUSPOSIXLocale];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setDateFormat:#"MMM dd, yyyy "];
self.date.text = [df stringFromDate:self.pickerView.date];
//NSString *strFirstPickerView = [_ty objectAtIndex:row];
//_providerType.text = strFirstPickerView;
}
}
- (void)updateLabel:(id)sender {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
//[df setLocale:enUSPOSIXLocale];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setDateFormat:#"MMM dd, yyyy "];
self.date.text = [df stringFromDate:self.pickerView.date];
}
- (IBAction)saveChanges:(UIBarButtonItem *)sender {
[self.obj setObject:self.topic.text forKey:#"Topic"];
[self.obj setObject:[NSNumber numberWithInt:self.pVotes.text.intValue] forKey:#"proVotes"];
[self.obj setObject:[NSNumber numberWithInt:self.cVotes.text.intValue] forKey:#"conVotes"];
[self.obj setObject:[NSNumber numberWithInt:self.abs.text.intValue] forKey:#"Abstentions"];
[self.obj setObject:self.pickerView.date forKey:#"Date"];
NSLog(#"Saving...");
[self.obj saveInBackground];
[self performSegueWithIdentifier:#"afterSave" sender:self];
//[self.navigationController popViewControllerAnimated:YES];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Section: %ld", (long)[indexPath section]);
NSLog(#"Row: %ld", (long)[indexPath row]);
if([indexPath section] == 1 && [indexPath row] == 0)
{
NSLog(#"Right Cell");
UIActionSheet *popupQuery = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:#"Delete Debate" otherButtonTitles:nil];
popupQuery.tag = 1;
[popupQuery showInView:self.view];
}
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if(actionSheet.tag == 1)
{
if(buttonIndex == 0)
{
[self.obj deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
[self performSegueWithIdentifier:#"afterSave" sender:self];
//[self loadObjects];
}];
}
}
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
if(pickerView == self.proPicker)
{
NSLog(#"First Log");
NSLog(#"In numComponents: %#",self.pStrings);
return 1;
}
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
if(pickerView == self.proPicker)
{
NSLog(#"Right Picker");
NSLog(#"Count in numRows: %lu", (unsigned long)[self.pStrings count]);
return [self.pStrings count];
}
//return [_ty count];
return [self.pStrings count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
if(pickerView == self.proPicker)
{
NSLog(#"Picked goooood");
return [self.pStrings objectAtIndex:row];
}
return [self.pStrings objectAtIndex:row];
}
#end
The fetchIfNeededInBackgroundWithBlock call is asynchronous.
This line:
[self.pStrings addObject:name];
fills in the data into self.pStrings.
You are expecting its values to be filled in by the time you hit this call:
[self.proPicker reloadAllComponents];
at the end of your viewDidLoad method. You somehow need to not reloadAllComponents until that data is loaded.
I would recommend adding a BOOL to track if you've already reloaded the components. If you have, just do it again at the end of fetching the data. Like this:
- (void)viewDidLoad
{
[super viewDidLoad];
__block BOOL hasCompletedSetup = NO;
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
//self.date = [[UIDatePicker alloc]init];
self.date.delegate = self;
self.pro.delegate = self;
self.con.delegate = self;
self.pVotes.delegate = self;
self.cVotes.delegate = self;
self.abs.delegate = self;
self.topic.delegate = self;
self.pickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 322, 0, 0)];
self.pickerView.datePickerMode = UIDatePickerModeDate;
self.pickerView.hidden = true;
self.pickerView.date = [NSDate date];
[self.pickerView addTarget:self
action:#selector(updateLabel:)
forControlEvents:UIControlEventValueChanged];
//[self.view addSubview:pickerToolbar];
[self.tableView addSubview:self.pickerView];
//self.pickerView.del
self.date.inputView = self.pickerView;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
//[df setLocale:enUSPOSIXLocale];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setDateFormat:#"MMM dd, yyyy "];
self.proPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 322, 0, 0)];
self.proPicker.hidden = true;
self.proPicker.delegate = self;
[self.tableView addSubview:self.proPicker];
self.pro.inputView = self.proPicker;
self.pStrings = [[NSMutableArray alloc]init];
self.cStrings = [[NSMutableArray alloc]init];
self.pChoices = [[NSMutableArray alloc]initWithArray:[self.obj objectForKey:#"PR"]];
self.cChoices = [[NSMutableArray alloc]init];
self.proTest = [[NSMutableArray alloc]init];
//self.pChoices = [self.obj objectForKey:#"PR"];
//self.cChoices = [self.obj objectForKey:#"CR"];
NSLog(#"Choices Now: %#", self.pChoices);
NSLog(#"Choices Count: %lu", (unsigned long)[self.pChoices count]);
for (PFUser *us in self.pChoices) {
//NSLog(#"Hi");
//PFUser *user = [self.pChoices objectAtIndex:i];
[us fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) {
//[self.pChoices addObject:object];
//NSString *name = [NSString stringWithFormat:#"%# %#", [object objectForKey:#"firstName"], [object objectForKey:#"lastName"]];
//NSLog(name);
//[self.proTest addObject:object];
//NSLog(#"The value before pStrings is: %#", name);
//[self.pStrings addObject:name];
//NSLog(#"This is spot: %#", [self.pStrings objectAtIndex:i]);
[self.proTest addObject:object];
NSString *name = [NSString stringWithFormat:#"%# %#", [object objectForKey:#"firstName"], [object objectForKey:#"lastName"]];
[self.pStrings addObject:name];
NSLog(#"Pro Test: %#", self.proTest);
NSLog(#"Pro Strings: %#", self.pStrings);
NSLog(#"User: %#", us);
NSLog(#"Object: %#", object);
}];
if (hasCompletedSetup) {
[self.proPicker reloadAllComponents];
}
}
NSLog(#"Strings: %#", self.pStrings);
NSLog(#"Pro Test: %lu", (unsigned long)[self.proTest count]);
//NSLog(#"%#", self.pStrings);
self.topic.text = [self.obj objectForKey:#"Topic"];
self.date.text = [df stringFromDate:[self.obj objectForKey:#"Date"]];
NSLog(#"Hi Test");
if([[NSString stringWithFormat:#"%#", [self.obj objectForKey:#"proVotes"] ] isEqualToString:#"0"])
{
NSLog(#"ITS NULL");
self.pVotes.text = #"";
}
//self.pVotes.text = [NSString stringWithFormat:#"%#", [self.obj objectForKey:#"proVotes"] ];
else
{
self.pVotes.text = [NSString stringWithFormat:#"%#", [self.obj objectForKey:#"proVotes"] ];
}
if([[NSString stringWithFormat:#"%#", [self.obj objectForKey:#"conVotes"] ] isEqualToString:#"0"])
{
self.cVotes.text = #"";
}
else
{
self.cVotes.text = [NSString stringWithFormat:#"%#", [self.obj objectForKey:#"conVotes"] ];
}
if([[NSString stringWithFormat:#"%#", [self.obj objectForKey:#"Abstentions"] ] isEqualToString:#"0"])
{
self.abs.text = #"";
}
else
{
self.abs.text = [NSString stringWithFormat:#"%#", [self.obj objectForKey:#"Abstentions"]];
}
/*
NSLog(#"Here");
NSLog(#"%#", proU);
self.pro.text = [NSString stringWithFormat:#"%# %#", [proU objectForKey:#"firstName"], [proU objectForKey:#"lastName"]];
PFUser *conU = [self.obj objectForKey:#"Con"];
//self.con.text = [NSString stringWithFormat:#"%# %#", [conU objectForKey:#"firstName"], [conU objectForKey:#"lastName"]];
*/
PFUser *proU = [self.obj objectForKey:#"Pro"];
[proU fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) {
self.pro.text = [NSString stringWithFormat:#"%# %#", [object objectForKey:#"firstName"], [object objectForKey:#"lastName"]];
}];
PFUser *conU = [self.obj objectForKey:#"Con"];
[conU fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) {
self.con.text = [NSString stringWithFormat:#"%# %#", [object objectForKey:#"firstName"], [object objectForKey:#"lastName"]];
}];
[self.pickerView setDate:[self.obj objectForKey:#"Date"]];
hasCompletedSetup = YES;
[self.proPicker reloadAllComponents];
}

TableView Not Showing All Rows For Blog

I have a number of blog apps. Recently, some of them started experiencing some issues. I use ASIHTTP Classes and GDataXML Classes to parse the xml of a wordpress feed, and put each item (article) into a mutable array. The tableview is then supposed to load all of the stories into a cell for each article. The issue I am having is that new articles are not being displayed on first run, the user is having to Pull to Refresh, and then the new article displays. I ran a test just now on an app. The article was posted a few hours ago. I ran the app, it wasn't there. Pulled to refresh, it showed. Closed down the app completely, restarted it, and it was gone again. Here is the code in the TableView's implementation:
#implementation RootViewController
- (void)refresh {
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feeds = [NSArray arrayWithObjects:#"http://bubblycandacebabbles.wordpress.com/?cat=-2008&feed=rss2",
nil];
for (NSString *feed in _feeds) {
NSURL *url = [NSURL URLWithString:feed];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[_queue addOperation:request];
}
}
- (void)viewDidLoad {
[super viewDidLoad];
[activity startAnimating];
//[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:#"navbarcopy.png"] forBarMetrics:UIBarMetricsDefault];
self.title = #"Blog";
CGFloat nRed=111.0/255.0;
CGFloat nBlue=209/255.0;
CGFloat nGreen=229.0/255.0;
UIColor *myColor=[[UIColor alloc]initWithRed:nRed green:nBlue blue:nGreen alpha:1];
UIBarButtonItem *font = [[UIBarButtonItem alloc] initWithTitle:#"Change Font Size" style:UIBarButtonItemStylePlain target:self action:#selector(fontsizes)];
self.navigationController.navigationItem.rightBarButtonItem = font;
self.tableView.backgroundColor = myColor;
self.refreshControl = [[UIRefreshControl alloc] init];
[self.refreshControl addTarget:self action:#selector(refreshInvoked:forState:) forControlEvents:UIControlEventValueChanged];
[self refresh];
}
-(void) refreshInvoked:(id)sender forState:(UIControlState)state {
// Refresh table here...
[_allEntries removeAllObjects];
[self.tableView reloadData];
[self refresh];
}
- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSString *blogTitle = [channel valueForChild:#"title"];
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = [item valueForChild:#"link"];
NSString *articleDateString = [item valueForChild:#"pubDate"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822];
NSString *articleImage = [item valueForChild:#"content:encoded"];
NSScanner *theScanner;
NSString *gt =nil;
theScanner = [NSScanner scannerWithString:articleImage];
NSString *comments = [articleUrl stringByAppendingString:#"#respond"];
NSString *commentslink = [NSString stringWithFormat: #"Leave A Comment",comments];
// find start of tag
[theScanner scanUpToString:#"alt=\"\" width=" intoString:NULL] ;
// find end of tag
[theScanner scanUpToString:#"/>" intoString:&gt] ;
// replace the found tag with a space
//(you can filter multi-spaces out later if you wish)
NSString *test = [articleImage stringByReplacingOccurrencesOfString:[ NSString stringWithFormat:#"%#", gt] withString:#"alt=\"\" width=\"150\" height=\"150\""];
NSString *final = [test stringByReplacingOccurrencesOfString:#"float:none;height:30px" withString:#"float:none;height:1px"];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSString *dateofarticle = [dateFormatter stringFromDate:articleDate];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *smalltitle = [defaults objectForKey:#"Title"];
NSString *smallbody = [defaults objectForKey:#"Article"];
NSString *bodyoftext = [[[[[[[[[[[#"<head><body bgcolor=\"#6fd1e5\" text=\"#CC0099\"><style type='text/css'>a > img {pointer-events: none;cursor: default;max-width: 310;}</style></head><b><font size=" stringByAppendingString: smalltitle ] stringByAppendingString:#"><div align=\"left\"><FONT FACE=\"noteworthy\">" ]stringByAppendingString:articleTitle] stringByAppendingString:#"</font></b><font size=" ] stringByAppendingString:smallbody ] stringByAppendingString:#"><div align=\"left\"><FONT FACE=\"noteworthy\">"] stringByAppendingString:dateofarticle] stringByAppendingString:#"</div></p><FONT FACE=\"noteworthy\">"] stringByAppendingString:final] stringByAppendingString:commentslink]stringByAppendingString:#"</FONT>"];
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate
articleImage:bodyoftext] autorelease];
[entries addObject:entry];
}
}
}
- (void)parseFeed:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
if ([rootElement.name compare:#"rss"] == NSOrderedSame) {
[self parseRss:rootElement entries:entries];
} else if ([rootElement.name compare:#"feed"] == NSOrderedSame) {
[self parseAtom:rootElement entries:entries];
} else {
NSLog(#"Unsupported root element: %#", rootElement.name);
}
}
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_allEntries count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[Cell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSString *substring = #"http://bubblycandacebabbles.files.wordpress.com";
NSRange textRange = [entry.articleImage rangeOfString:substring];
if(textRange.location != NSNotFound){
NSString *thearticleImage = entry.articleImage;
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:#"src=\"([^\"]+)\"" options:NSRegularExpressionCaseInsensitive error:NULL];
NSString *someString = thearticleImage;
NSString *oneurl = [someString substringWithRange:[expression rangeOfFirstMatchInString:someString options:NSMatchingCompleted range:NSMakeRange(0, [someString length])]];
NSString *finalstring = [oneurl stringByReplacingOccurrencesOfString:#"src=\"" withString:#""];
NSString *thefinalstring = [finalstring stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
CGFloat nRed=204.0/255.0;
CGFloat nBlue=0/255.0;
CGFloat nGreen=153.0/255.0;
UIColor *myColortext=[[UIColor alloc]initWithRed:nRed green:nBlue blue:nGreen alpha:1];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
UIFont *cellFont = [UIFont fontWithName:#"noteworthy" size:16];
UIFont *cellFont2 = [UIFont fontWithName:#"noteworthy" size:12];
CALayer * l = [cell.imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:11];
[l setBorderWidth:2.0];
[l setBorderColor:[[UIColor blackColor] CGColor]];
cell.textLabel.text = entry.articleTitle;
cell.textLabel.numberOfLines = 2;
cell.detailTextLabel.adjustsFontSizeToFitWidth = YES;
cell.detailTextLabel.text = [NSString stringWithFormat:#"%# - Mother May I Blog", articleDateString];
cell.textLabel.font = cellFont;
cell.detailTextLabel.font = cellFont2;
cell.textLabel.textColor = myColortext;
cell.detailTextLabel.textColor = myColortext;
[cell.imageView setImageWithURL:[NSURL URLWithString:thefinalstring] placeholderImage:[UIImage imageNamed:#"iphoneicon#2x.png"]];
}
else {
CALayer * l = [cell.imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:11];
[l setBorderWidth:2.0];
[l setBorderColor:[[UIColor blackColor] CGColor]];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
UIFont *cellFont = [UIFont fontWithName:#"noteworthy" size:16];
UIFont *cellFont2 = [UIFont fontWithName:#"noteworthy" size:12];
cell.imageView.image = [UIImage imageNamed:#"iphoneicon#2x.png"];
cell.textLabel.text = entry.articleTitle;
cell.textLabel.numberOfLines = 2;
cell.detailTextLabel.adjustsFontSizeToFitWidth = YES;
cell.detailTextLabel.text = [NSString stringWithFormat:#"%# - Mother May I Blog", articleDateString];
CGFloat nRed=204.0/255.0;
CGFloat nBlue=0/255.0;
CGFloat nGreen=153.0/255.0;
UIColor *myColortext=[[UIColor alloc]initWithRed:nRed green:nBlue blue:nGreen alpha:1];
cell.textLabel.font = cellFont;
cell.detailTextLabel.font = cellFont2;
cell.textLabel.textColor = myColortext;
cell.detailTextLabel.textColor = myColortext;
}
return cell;
}
You need to invoke
[self.tableView reloadData];
at some point after your data has finished loading. How exactly you do this is a bit tricky, you need some way of telling when your operation queue is empty. Alternatively, you could theoretically call it after each operation in the queue is complete, that way the table will populate one at a time. This could cause problems if the user is on a slow connection, as reloading the table can cause jumps in the user experience, and I'm not positive on the thread safety of calling reloadData from a different thread

Resources