Filtering json data and reloading the resulted data into myTableView

112 Views Asked by At

Im trying to load an events(data) (from json file) that matches today's date into my tableView when the today's button is pressed then only the data with today's date will be loaded there and when the future button is pressed the events with later dates will be loaded, the only problem I have here is when i run my program nothing is actually happening when I press in either of these UIbuttons, I got all the events regardless their date and without even clicking on any UIButton, u can see below some of my code, it would be great if someone could figure out what is the problem there and since Im not quiet sure about how to use predicate to filter the data:

@property (strong, nonatomic) NSArray *dateEvents;

@end


@implementation HomeViewController {
 NSArray *_events;
 NSArray *_dateEvents;


 }



- (IBAction)upcomingEvents:(id)sender {


NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd-MM-YYYY"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSLog(@"mama"); 

_dateEvents = [_events filteredArrayUsingPredicate:[NSPredicate   predicateWithBlock:^BOOL(Events * event, NSDictionary *bindings){

    return [event.date isEqualToString:dateString];
    }]];
         self.myTableView.dataSource = self;


         [self.myTableView reloadData];
         NSLog(@"yes");

  }

Thanks,

1

There are 1 best solutions below

5
onepointsixtwo On

I'm not sure this will definitely help, because I can't see enough code so be certain that this is your problem, but you might find it useful to convert all the dates to NSDate objects (so that you can be certain that the problem is NOT that the strings are actually not equal), and then check whether the day is the current day, or not, by using this category method on NSDate:

NSDate+Extensions.m:

static NSCalendar* ___calendar;

@implementation NSDate (Extensions)

    - (BOOL)isSameDay:(NSDate*)date
{
    NSCalendar* calendar = [NSCalendar currentCalendar];

    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:self];

    return [comp1 day]   == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year]  == [comp2 year];
}

-(NSCalendar*)currentCalendar
{
    if(___calendar == nil)
    {
        ___calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    }

    return ___calendar;
}

@end

NSDate+Extensions.h

@interface NSDate (Extensions)

- (BOOL)isSameDay:(NSDate*)date;

@end