I have an array of objects that contain NSDate property in them. And I'm populating them successfully in a UITableView.
I want to distribute them (the objects) in UITableView sections according to their month.
How can I do that?
Please review this code once.It may help you.
NSMutableDictionary * dictArrData; //declare dictionary global
-(void)createHederAndCellArray
{
dictArrData=[[NSMutableDictionary alloc]init];
for(int i=0;i<arrHistory.count;i++)
{
yourObject *pastorders=[arrHistory objectAtIndex:i];
if([dictArrData objectForKey:pastorders.paymentDate])
{
NSMutableArray *arrTemp=[dictArrData objectForKey:pastorders.paymentDate];
[arrTemp addObject:pastorders];
[dictArrData setObject: arrTemp forKey:pastorders.paymentDate];
}
else
{
NSMutableArray * arrTemp = [[NSMutableArray alloc]init];
[arrTemp addObject:pastorders];
[dictArrData setObject: arrTemp forKey:pastorders.paymentDate];
}
}
NSLog(#“check dictionary %#",[dictArrData description]);
}
[self createHederAndCellArray]; ----> this method you need to call after adding data in your array and than set code in tableview as below.
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [dictArrData allKeys].count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSArray *allValues=(NSArray*)[dictArrData objectForKey:[[dictArrData allKeys] objectAtIndex:section]];
return [allValues count];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 22, tableView.frame.size.width,15)];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width,25)];
[label setFont:[UIFont systemFontOfSize:14]];
label.textAlignment=NSTextAlignmentLeft;
label.textColor=[UIColor whiteColor];
NSString *sectionTitle=[NSString stringWithFormat:#"%#" ,[[dictArrData allKeys] objectAtIndex:section]];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd HH:mm:ss";
NSDate *date = [dateFormatter dateFromString:sectionTitle];
dateFormatter.dateFormat = #“MMM";
NSString *sectionTitle =[NSString stringWithFormat:#" %#", [dateFormatter stringFromDate:date]];
[view addSubview:imgvw];
[view addSubview:label];
[label setText:sectionTitle];
return view;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
yourcell *cell = [tableView dequeueReusableCellWithIdentifier:#“yourcellidentifier” forIndexPath:indexPath];
if (cell == nil)
{
cell = [[yourcell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"yourcellidentifier"];
}
#try
{
//keyArr=[self sortKeyAccordingTodate];
NSArray *allValues=[dictArrData objectForKey:[[dictArrData allKeys] objectAtIndex:indexPath.section]];
if(allValues.count >0 )
{
yourObject *pastorder=[allValues objectAtIndex:indexPath.row];
cell.lblProductname.text=pastorder.itemName;
}
}
#catch (NSException *exception) {
NSLog(#"Exception :%#",exception.description);
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 25;
}
To sort according to date than you need to sort dictionary keys.
-(NSArray *)sortKeyAccordingTodate
{
NSArray* sorted = [[dictArrData allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2)
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
dateFormatter.dateFormat = #"yyyy-MM-dd HH:mm:ss";
NSDate *date = [dateFormatter dateFromString:obj1];
NSDate *date1 = [dateFormatter dateFromString:obj2];
if (date > date1) {
return (NSComparisonResult)NSOrderedAscending;
}
if (date < date1) {
return (NSComparisonResult)NSOrderedDescending;
}
return (NSComparisonResult)NSOrderedSame;
}];
return sorted;
}
if you use sort method than you need to use [self sortKeyAccordingTodate] instead [dictArrData allKeys]
Hope this will help you :)
You can group the objects (e.g. Person) by using below code:
NSMutableArray* arrObjects = [NSMutableArray new];
for (int i=0;i<12;i++) {
Person* p1 = [Person new];
p1.name = [NSString stringWithFormat:#"ABC %d", i+1];
p1.date = [[NSDate date] dateByAddingTimeInterval:60*60*24*30*i];
[arrObjects addObject:p1];
}
// add blank arrays for 12 months
NSMutableArray* matrixObjects = [NSMutableArray new];
for (int i=0; i<12; i++) {
[matrixObjects addObject:[NSMutableArray new]];
}
NSCalendar* calendar = [NSCalendar currentCalendar];
for (Person* p in arrObjects) {
int month = (int) [[calendar components:NSCalendarUnitMonth fromDate:p.date] month];
[matrixObjects[month-1] addObject:p];
}
// print resutls
for (int i=0; i<matrixObjects.count; i++) {
NSLog(#"Objects in Section %d", i);
for (Person* p in matrixObjects[i]) {
NSLog(#" ROW: %# %#", p.name, p.date.description);
}
}
Which gives output as below:
Objects in Section 0
ROW: ABC 11 2017-01-29 11:55:49 +0000
Objects in Section 1
ROW: ABC 12 2017-02-28 11:55:49 +0000
Objects in Section 2
Objects in Section 3
ROW: ABC 1 2016-04-04 11:55:49 +0000
Objects in Section 4
ROW: ABC 2 2016-05-04 11:55:49 +0000
Objects in Section 5
ROW: ABC 3 2016-06-03 11:55:49 +0000
Objects in Section 6
ROW: ABC 4 2016-07-03 11:55:49 +0000
Objects in Section 7
ROW: ABC 5 2016-08-02 11:55:49 +0000
Objects in Section 8
ROW: ABC 6 2016-09-01 11:55:49 +0000
Objects in Section 9
ROW: ABC 7 2016-10-01 11:55:49 +0000
ROW: ABC 8 2016-10-31 11:55:49 +0000
Objects in Section 10
ROW: ABC 9 2016-11-30 11:55:49 +0000
Objects in Section 11
ROW: ABC 10 2016-12-30 11:55:49 +0000
matrixObjects is the array of 12 month wise array of you objects, which you can use in numberOfSections and numberOfRows delegate methods
Related
How to filter tableview based on a picker value?
I have the following NSMutableArray:
[0]:Object 1 (name1, October)
[1]:Object 2 (name2, November)
[2]:Object 3 (name3, March)
[3]:Object 4 (name4, April)
[4]:Object 5 (name5, April)
The table view displays the value of these objects.
and I have a picker with month values (January, February,... etc)
so based on the user selection of picker value, the table view should display values for example if I choose month April, only these values object 3 and 4 should appear.
Solution code, thanks to Fennelouski: (just thought I'd put it here In case someone needs it)
NSMutableArray *array;
NSMutableArray *filteredArray;
int monthInt;
NSString *monthString;
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Titles *object1 = [[Titles alloc]init];
[object1 setTitle:#"Title1"];
[object1 setMonth:#"10"];
Titles *object2 = [[Titles alloc]init];
object2.title = #"Title2";
object2.month = #"10";
Titles *object3 = [[Titles alloc]init];
object3.title = #"Title3";
object3.month = #"4";
array = [[NSMutableArray alloc]init];
filteredArray = [[NSMutableArray alloc]init];
[array addObject:object1];
[array addObject:object2];
[array addObject:object3];
pickerData = #[#"Jan", #"Feb", #"March", #"April", #"May", #"June", #"July", #"Aug", #"Sept", #"October", #"Nov", #"Dec"];
NSDate *currentDate = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:currentDate];
monthInt= [components month];
monthString = [NSString stringWithFormat:#"%li",(long)monthInt];
for (Titles *item in array)
{
if([item.month isEqualToString:monthString])
{
[filteredArray addObject:item];
}
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [filteredArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
Titles *titles = filteredArray[indexPath.row];
cell.textLabel.text = titles.title;
cell.imageView.image = [UIImage imageNamed:#"totoro.jpg"];
NSLog(#"Cell is %#", [array objectAtIndex:indexPath.row]);
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (int)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
// The number of rows of data
- (int)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return pickerData.count;
}
// The data to return for the row and component (column) that's being passed in
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return pickerData[row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSLog(#"Row: %li", (long)row);
monthString = [NSString stringWithFormat:#"%li",row+1];
[filteredArray removeAllObjects];
for (Titles *item in array)
{
if([item.month isEqualToString:monthString])
{
[filteredArray addObject:item];
}
}
[self.tableview reloadData];
}
It seems like you're following the design pattern of having your table view represent information stored in a separate data structure. That's good and makes filtering much easier.
Fortunately, you don't have to really do much with the table view to filter the results. All you need to do is filter the data structure that your table view is reading from and then update the table view.
I'd recommend adding an array in between your mutable array and the table view.
Something like this should work well for you
NSMutableArray *filteredObjects = [NSMutableArray new];
for (MYObjectClass *object in myMutableArray) {
if ([object.stringProperty isEqualToString:#"Filter"]) {
[filteredObjects addObject:object];
}
}
Then have your table view reference filteredObjects rather than the array you're using that has all of your data.
I have been struggling for this issue for two week now. but by the help of StackOverflow people I have came up with 95% successful implementation..
Here is my problem.. and now I could load my results with the picker cell [First most cell] when the date is selected.
Now I have another issue...when i run my application at first time, it is works as I expected..but when i tap the first most cell to pick a different date , then the application crashed..
Here is the log output...
below is my codes for the implementation
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSDictionary* reqFdate= [ScheduleView getRequestForDate];
if (reqFdate.count == 0) {
NSInteger numberOfRows = [self.persons count];
if ([self datePickerIsShown]){
numberOfRows++;
}
return numberOfRows;
}
else{
return reqFdate.count + 1;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *currentTime = [dateFormatter stringFromDate:today];
NSDate *date=[dateFormatter dateFromString:currentTime];
if(indexPath.row==0){
VCPerson *person = self.persons[0];
cell = [self createPersonCell:person];
}
else if ([self datePickerIsShown] && (self.datePickerIndexPath.row == 1)){
// VCPerson *person = self.persons[indexPath.row -1];
cell = [self createPickerCell:date];
}
else{
cellForDatePickCell *cell = (cellForDatePickCell*)[self.tableView dequeueReusableCellWithIdentifier:kOtherCellIdentifier];
cell.delegate_Dtepick = self;
return cell;
}
if(indexPath.section!=0 && tapfirstCell) {
UITableViewCell *cell = (UITableViewCell*)[self.tableView dequeueReusableCellWithIdentifier:kOtherCellIdentifier forIndexPath:indexPath];
//cell.delegate_Dtepick = self;
NSDictionary *dictionary = [_dataArray objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"data"];
NSString *cellValue = [array objectAtIndex:indexPath.row];
cell.textLabel.text =cellValue;
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self.tableView beginUpdates];
if ([self datePickerIsShown] && (self.datePickerIndexPath.row - 1 == indexPath.row)){
[self hideExistingPicker];
// [self.tableView reloadData];
//[self viewDidLoad];
//call the service and take the results
NSString* selecteDate = [ScheduleView getDate];
NSString* prsonID =[LoginView getPersonID];
NSDictionary* parms = [NSDictionary dictionaryWithObjectsAndKeys:prsonID,#"caregiverPersonId",selecteDate,#"selectedDate", nil];
jsonpaser* jp = [[jsonpaser alloc]init];
[jp getWebServiceResponce:#"http://qa.vardle.com/Mobile/WebServices/AppointmentService.asmx/GetAppointments" :parms success:^(NSDictionary *responseObject)
{
requestsF_date = responseObject;
NSLog(#"RESPONSEFORDATE_IN DIDSELECT :%#",requestsF_date);
NSArray* indexpaths = [self getIndexPaths];
NSLog(#"indexPATHS %#",indexpaths);
[self.tableView reloadData];
}];
// cellForDatePickCell *cell = (cellForDatePickCell*)[self.tableView dequeueReusableCellWithIdentifier:kOtherCellIdentifier forIndexPath:indexPath];
// cell.delegate_Dtepick = self;
//tapfirstCell = true;
/*
cellForDatePickCell *cell=(cellForDatePickCell*)[tableView cellForRowAtIndexPath:indexPath];
if(![cell.textLabel.text isEqualToString:#"5/23/14"])
{
return;
}
*/
if (tapfirstCell==false) {
tapfirstCell = true;
}
else{
tapfirstCell = false;
}
}else {
NSIndexPath *newPickerIndexPath = [self calculateIndexPathForNewPicker:indexPath];
if ([self datePickerIsShown]){
[self hideExistingPicker];
}
[self showNewPickerAtIndex:newPickerIndexPath];
self.datePickerIndexPath = [NSIndexPath indexPathForRow:newPickerIndexPath.row + 1 inSection:0];
}
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
[self.tableView endUpdates];
}
please someone tell me where is the issue..why app is crashed when i try to pick a date second time..
please help
i have fix my issue... i didnt deleted the rows before i start to show the date picker again..
here is the full code
here what i did was : i use Inline Datepicker with the table view [date picker will show by selecting the first cell of the table view].according to the date selected from the picker, i am displaying my custom cells below the first cell.[because the first cell always there to pick a date from a date picker].
if someone want to do the same thing which i did i think my code will help you
thank you
I am creating such table view which has not specified the number of sections (that means number of sections should be specified dynamically in its respected delegate i.e. - -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView) or not specified the rows in each sections (That means the number of rows in each sections also should be specified by dynamically in its respected delegates i.e.- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section) as below image in which the section of table specifies the month with year and each section can have any number of rows. The image is -
as above image january 2014 section has 4 rows and december 2013 has 2 rows. I would like to create such type of table view. Is it possible ? if it is possible than please provide proper way or any example or any link through which I can achieve it. Thanks in advanced.
Please Use below Code. Hope It will be useful to u.
in .h file defile
int i
in viewdidload method of .m file
arrData = [NSMutableArray array];
int temp = 1;
for (i = 0; i < 5; i++) {
NSMutableArray * arrIndexData = [NSMutableArray array];
for (int j = 0; j<=i; j++,temp++) {
[arrIndexData addObject:[NSString stringWithFormat:#"%d",temp]];
}
[arrData addObject:arrIndexData];
}
Now in numberOfSectionsInTableView
return i;
in numberOfRowsInSection
return [arrData count];
in cellForRowAtIndexPath
static NSString *CellIdentifier = #"Cell";
CustomCell * cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
[cell reloadTableWithArrData:[arrData objectAtIndex:indexPath.row]];
return cell;
I hope, this ll help u..
#Jekil , Just set Your DateFormatter to MMMM yyyy ,
Check my updated Answer
As all suggests use Array of Dictionary in Dictionary put two object one for Title (Nsstring) and second is NSArray ( dict for cell detail),
I have implemented One method for that in my app,
NOTE: Use Your Key Values for your data.
Use Following code for Arranging Array,
-(NSMutableArray*)arrangeSection:(NSMutableArray *)source
{
NSDateFormatter *_formatter=[[NSDateFormatter alloc]init];
[_formatter setLocale:[NSLocale currentLocale]];
[_formatter setDateFormat:#"MMMM yyyy"];
NSMutableArray *arrayMain=[NSMutableArray array];
for (int i=0; i<source.count; i++){
NSDictionary *dict=source[i];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[dict objectForKey:#"StartDate"]doubleValue]];
NSString *mm=[_formatter stringFromDate:date];
NSMutableDictionary *secDict=[NSMutableDictionary dictionary];
NSMutableArray *secArray=[NSMutableArray array];
if (i==0){
[secDict setObject:mm forKey:#"Month"];
[secArray addObject:dict];
[secDict setObject:secArray forKey:#"Data"];
[arrayMain addObject:secDict];
}
else{
BOOL flg=NO;
for (NSDictionary *dict2 in arrayMain){
if([[dict2 objectForKey:#"Month"]isEqualToString:mm]){
flg=YES;
[[dict2 objectForKey:#"Data"]addObject:dict];
break;
}
}
if (!flg){
[secDict setObject:mm forKey:#"Month"];
[secArray addObject:dict];
[secDict setObject:secArray forKey:#"Data"];
[arrayMain addObject:secDict];
}
}
}
return arrayMain;
}
Now in tableview Methods use as,
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return arrayEvents.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[arrayEvents[section]objectForKey:#"Data"]count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
...
NSDictionary *aDict = [arrayEvents objectAtIndex:indexPath.section];
NSDictionary *maindict=[[aDict objectForKey:#"Data"]objectAtIndex:indexPath.row];
...
}
I'm trying to make an app with a calendar being displayed and as soon as a day on the calendar (each day is a UIView with a tap gesture) is tapped, all calendar appointments for that day should be displayed in a UITableView. I've got this working, but there's a big lag between when the tap occurs and when the data is actually populated into the UITableView. Here's my code:
EKEventStore *store = [[EKEventStore alloc] init];
//Access Granted to Calendar by user
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
// Create the start date components
NSDateFormatter *startFormatter = [[NSDateFormatter alloc]init];
[startFormatter setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSString *monthNumberString = [NSString stringWithFormat:#"%i", month];
NSString *startDateString = [[[[[monthNumberString stringByAppendingString:#"/"] stringByAppendingString:dLabel.text] stringByAppendingString:#"/"] stringByAppendingString:yearString] stringByAppendingString:#" 12:01 am"];
NSDate *start = [startFormatter dateFromString:startDateString];
NSLog(#"Start Date: %#", startDateString);
// Create the end date components
NSDateFormatter *endFormatter = [[NSDateFormatter alloc]init];
[endFormatter setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSString *endDateString = [[[[[monthNumberString stringByAppendingString:#"/"] stringByAppendingString:dLabel.text] stringByAppendingString:#"/"] stringByAppendingString:yearString] stringByAppendingString:#" 11:59 pm"];
NSDate *end = [endFormatter dateFromString:endDateString];
NSLog(#"End Date: %#", endDateString);
// Create the predicate from the event store's instance method
NSPredicate *predicate = [store predicateForEventsWithStartDate:start
endDate:end
calendars:nil];
// Fetch all events that match the predicate
events = [store eventsMatchingPredicate:predicate];
//Sort the array
events = [events sortedArrayUsingSelector:#selector(compareStartDateWithEvent:)];
int eventCount = [events count];
NSLog(#"%i", eventCount);
for (int i=0; i<eventCount; i++) {
EKEvent *theEvent = [events objectAtIndex:i];
NSLog (#"Element %i = %#", i, theEvent.title);
}
UITableView *dayTableView = [[UITableView alloc] initWithFrame:CGRectMake(360, 0, 300, 550)
style:UITableViewStylePlain];
dayTableView.backgroundColor = lightBlueColor;
dayTableView.separatorColor = [UIColor clearColor];
dayTableView.delegate = self;
dayTableView.dataSource = self;
[super addSubview:dayTableView];
}];
UITableview Delegate Functions:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSLog (#"I made a section!");
return 1; //count of section
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog (#"I made %i rows!", [events count]);
return [events count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *c = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"mycell"];
EKEvent *theEvent = [events objectAtIndex:indexPath.row];
c.textLabel.text = theEvent.title;
NSLog (#"Cell %i = %#", indexPath.row, theEvent.title);
//c.textLabel.text = #"Calendar Event Goes Here";
c.textLabel.textColor = [UIColor whiteColor];
//NSLog (#"I made a cell!");
return c;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 35;
}
Any help would be greatly appreciated.
Without profiling it is difficult to say what the bottleneck of your code is. However, based on previous experience I would say that it is the lines that looks like
NSString *startDateString = [[[[[monthNumberString stringByAppendingString:#"/"] stringByAppendingString:dLabel.text] stringByAppendingString:#"/"] stringByAppendingString:yearString] stringByAppendingString:#" 12:01 am"];
At least if it is called +20000x (or something) a second. First of all it would be more convienient to write this as
NSString *startDateString = [NSString stringWithFormat:#"%#/%#/%# 12:01 am", monthNumberString, dLabel.text, yearString];
But I fear this would not speed up your program much. I would recommend going back to plain C code and use e.g. sprintf instead. You can look up the syntax of it here as well as some examples of use.
I found the answer. The problem is here:
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
the way that the event store is accessed is different on iOS6 and iOS5. Here's a link that shows the correct way of doing it:
http://fostah.com/ios/2012/09/28/ios6-event-edit.html
Now I meet a strange situation, I need your help, and forgive my poor English.
When a UITableView, filled with NSArray, on the top, really reload data when I use [UITableView reloadData]. But, the table doesn't reload data if it's not on the top side. In fact, the app crashed. The strange thing is that the indexPath.section isn't the right value, bigger than real value. So the console said: index 2 beyond bounds [0..1].
Does anybody know why? Please give me a hand or a tips.
Below are some codes:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (pageCount == 0) {
[[NSNotificationCenter defaultCenter] postNotificationName:#"IPOCalendarTableTitle" object:nil];
return 0;
} else {
NSMutableArray *arrayMonths = [stockArray objectAtIndex:pageIndex];
NSMutableArray *arrayDays = [arrayMonths objectAtIndex:0];
IPOListing *listing = [arrayDays objectAtIndex:0];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyy/MM/dd";
NSDate *date = [formatter dateFromString:listing.date];
NSString *s = nil;
NSArray *arrayMonthEN = [NSArray arrayWithObjects:#"Jan", #"Feb", #"Mar", #"Apr", #"May", #"Jun", #"Jul", #"Aug", #"Sep", #"Oct", #"Nov", #"Dec", nil];
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if ([delegate.currentLanguage isEqualToString:#"SC"]) {
formatter.dateFormat = #"yyyy年M月";
s = [formatter stringFromDate:date];
} else if ([delegate.currentLanguage isEqualToString:#"TC"]) {
formatter.dateFormat = #"yyyy年M月";
s = [formatter stringFromDate:date];
} else if ([delegate.currentLanguage isEqualToString:#"EN"]) {
int year = [[listing.date substringWithRange:NSMakeRange(0, 4)] intValue];
int month = [[listing.date substringWithRange:NSMakeRange(5, 2)] intValue];
s = [NSString stringWithFormat:#"%#, %d", [arrayMonthEN objectAtIndex:month - 1], year];
}
[formatter release];
NSArray *array = [NSArray arrayWithObjects:s, [NSNumber numberWithInt:pageCount], [NSNumber numberWithInt:pageIndex], nil];
[[NSNotificationCenter defaultCenter] postNotificationName:#"IPOCalendarTableTitle" object:array];
NSLog(#"%d", [arrayMonths count]);
return [arrayMonths count];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSMutableArray *arrayMonths = [stockArray objectAtIndex:pageIndex];
NSMutableArray *arrayDays = [arrayMonths objectAtIndex:section];
return [arrayDays count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 36.0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"IPOCalendarCellIdentifier";
IPOCalendarCell *cell = (IPOCalendarCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"IPOCalendarCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.lineLabel.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1.0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSLog(#"%d, %d", indexPath.section, indexPath.row);
NSMutableArray *arrayMonths = [self.stockArray objectAtIndex:pageIndex];
NSMutableArray *arrayDays = [arrayMonths objectAtIndex:indexPath.section];
IPOListing *listing = [arrayDays objectAtIndex:indexPath.row];
// configuration the cell...
return cell;
}
If indexPath.section isn't the right value, I'm pretty sure it has something to do with the value you return in - (NSInteger) numberOfRowsInSection:(UITableView *)tableView
Check this first, because If the size of your array is two, so as the value return by numberOfRowsInSection:, indexPath.section can't be equal or greater than this value.
Fixed. The problem is not here, it is about that two gang tables. When I use [UITableView setContentOffset] to table A, B will refresh too. In this case table A will reloadData twice, and when contentOffset of table is zero, it will reloadData only once. When table reloadData twice in quick time, it crashes. Thank all of you and I feel so sorry for my mistake.