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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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?
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.
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.
@Jacob use isKindOfClass since both objects are probably subclasses of NSObject, or they could be subclasses of some other higher level object.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.