1

In my NSArray, I have two types of objects, let's say objects of class A and class B. I want to sort these objects, by comparing "startingDate" property of class A to "endingDate" property of class B. And I don't know how to make a comparison based on two different properties of different classes.

What's the best way to do this?

aslı
  • 8,740
  • 10
  • 59
  • 80

2 Answers2

2

Blocks are what you want, take a look at this question: How to sort an NSMutableArray with custom objects in it?

In the blocks example on that question, just have class A use startingDate and class B use ending date.

Community
  • 1
  • 1
rooftop
  • 3,031
  • 1
  • 22
  • 33
  • Yes I saw that, but all the block methods were comparing the same type of objects. I mean the block's arguments are id obj1 and id obj2, but then they're cast to the same classes. Now that I have two different types of objects, won't casting be a problem? How will I know which argument to cast to my first class? – aslı Feb 10 '12 at 17:08
  • 1
    You could check to see what kind of class obj1 and obj2 are by using [[(obj1/obj2) class] isSubclassofClass: [TargetClass class]] and then dealing with appropriately. – SushiGrass Jacob Feb 10 '12 at 17:25
  • Of course, but it's kind of messy to do so. I'll go that way if there aren't any better options though, thanks. – aslı Feb 10 '12 at 17:31
  • 2
    @Jacob use `isKindOfClass` since both objects are probably subclasses of `NSObject`, or they could be subclasses of some other higher level object. – Jack Lawrence Feb 16 '12 at 22:59
0

I would recommend an if/else block and the use of the statement

[myObject isKindOfClass:[ClassA class]]

Which returns a BOOL

If you'd rather (or in conjunction), Apple recommends using

[myObject respondsToSelector:@selector(startingDate)]

Which also returns a BOOL.

Blocks aren't really relevant in this situation; You could use this design pattern inside a plain method implementation, blocks, a for/while loop, or anywhere else.

Jack Lawrence
  • 10,664
  • 1
  • 47
  • 61