Get the Max date from the Array using KVC (Key-value coding)

Key-value coding is a mechanism for accessing an object’s properties indirectly, using strings to identify properties, rather than through invocation of an accessor method or accessing them directly through instance variables. In essence, key-value coding defines the patterns and method signatures that your application’s accessor methods implement.

Get the Max date from the Array using KVC (Key-value coding)

NSArray * dateArray = [NSArray arraywithobjects:@"2015-12-29",
@"2015-12-05",@"2015-12-12",@"2015-12-15",@"2015-12-30",nil];
NSDate *maxDate = [dateArray valueForKeyPath:@"@max.self"];
NSLog(@"max date is %@",maxDate);

Get the Max date from the Array without using KVC

NSArray * dateArray = [NSArray arraywithobjects:@"2015-12-29",
@"2015-12-05",@"2015-12-12",@"2015-12-15",@"2015-12-30",nil];

NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd"];
NSDate *latestDate  = [df dateFromString:dateArray[0]];
for (int i = 1; i<dateArray.count; i++)
{   
    NSDate *compareDate = [df dateFromString:dateArray[i]];
    latestDate = [latestDate laterDate:compareDate];
}
NSLog(@"max date is %@",maxDate);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s