1

So I have an NSArray with custom objects called Church. And in each church there is an array of mass times. So there is a method in church which calculates the closest mass to the user's current time.

-(NSDate *)closestTimeTo:(NSDate *)currentTime

I want to be able to sort the NSArray of Church by the results (which are NSDate) returned by that method for each object. Basically to get a sorted list of masses sorted by the closest time and also location.

I'm using categories and can't store the closest times as properties since its a core data object. I also don't think its a good idea to save those values to core data as these methods will be called constantly due to location services.

Any ideas on how I can sort such array using the result of its objects' method?

2 Answers 2

2

Try the following block. It would help directly(or at least with minor modifications).

NSArray *sortedArray;
sortedArray = [yourArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    NSDate *first = [(Church*)a closestTimeTo:currentTime];
    NSDate *second = [(Church*)b closestTimeTo:currentTime];
    return [first compare:second];
}];
Sign up to request clarification or add additional context in comments.

Comments

1

Make a new method in your class that takes another Church class and returns NSOrderedSame, NSOrderedAscending or NSOrderedDescending, depending on whether you want that object to be first or last. Use your closestTimeTo method to find that out. Then use NSArray's sortedArrayUsingSelector call with your method.

1 Comment

sounds interesting i'll have to try these types out

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.