0

I want to know whether the below code of line is valid in objective C

  if (dtDay < [m_array objectAtIndex:m_histCount-1]);

                       OR

  if (dtDay < [m_array objectAtIndex:i+1]);

here m_array is of NSMutableArray type.....

also this line of code

NSDate *date = [self getDate];

Regards Ranjit

Ranjit
  • 4,576
  • 11
  • 62
  • 121

2 Answers2

3
[m_array objectAtIndex:m_histCount-1]

and

[m_array objectAtIndex:i+1]

will return an object, and you can't test an object with <. That means these two lines are invalid.

However, in any situation where you'd expect an object, getting them directly from the array would work. This even works:

if([[[m_array objectAtIndex:i+1] date] timeIntervalSinceDate:[m_array objectAtIndex:m_histCount-1] < 0])

That is, it works if those indexes return NSDate objects.

Since arrays could contain any kind of object, it's best to make sure the object you get is of the correct type.

Edit:

It turns out you can compare objects with the < and > operands, but it's not useful. You're comparing their pointer values, which is just a pretty much random id. This does mean your lines are valid, I guess, but not really useful.

Source: How to compare objects using operator < or > in Objective-C?

Community
  • 1
  • 1
Aberrant
  • 3,423
  • 1
  • 27
  • 38
0

You can compare NSDate objects with the compare: laterDate: or earlierDate: selectors

NSComparisonResult result = [date1 compare:date2];
NSDate* earlierDate = [date1 earlierDate:date2];
NSDate* laterDate = [date1 laterDate:date2];

You can also sort the entire NSArray of dates in one go:

NSArray* sortedDateArray = [dateArray sortedArrayUsingSelector:@selector(compare:)];

The line:

NSDate *date = [self getDate];

Is valid if the self responds to the getDate selector and returns an NSDate (or subclass, which is unlikely).

jbat100
  • 16,757
  • 4
  • 45
  • 70