1
votes

I have a custom class in Obj-C called RouteManager which contains an array of NSStrings. Each string is a bus stop name which is used as a key for a dictionary to get the rest of the information for the bus stop (basically, just [busStopDictionary allkeys]). In one of the situations where my app uses this array, I want to return the array sorted by the distance from the user. I've started setting up the code to be able to call sortedArrayUsingSelector on my array with the following method:

- (NSComparisonResult)compareByDistance:(NSString*) otherStop
{
    // Return appropriate NSOrdered enum here based on comparison of
    // self and otherStop
}

My problem is that in the case where compareByDistance is a method of RouteManager, self refers to the instance of RouteManager. However, I need self to refer to the NSString that the compare is being called on. So, I assumed I needed to setup a category, as such:

@interface NSString (Support)
-(NSComparisonResult) compareByDistance:(NSString*)otherStop;
@end

This got my self reference correct, however this comparison uses values from the RouteManager class. When implemented as seen above, the NSString (Support) implementation obviously complains that those values are undeclared.

That should provide enough background info for my question. How do I go about doing this? I would like my category of NSString, which consists solely of the method compareByDistance, to be able to use values from the current instance of my class, RouteManager, which inherits from NSObject. Ideally, I feel as though the category should somehow be within RouteManager. I feel there has to be some way to accomplish this that is cleaner than passing the necessary values into compareByDistance. Thanks in advance for any and all help.

1
Can you show an example of how you expect comparebyDistance: to be used? As-is, it appears that you want the method to belong to NSString, and it would take an NSString parameter, so how would RouteManager enter into anything?Kristopher Johnson
// stopNames is the array of bus stop names from [busStopDictionary allkeys] NSArray *stopsSortedByDistance = [stopNames sortedArrayUsingSelector:@selector(compareByDistance:)]; compareByDistance needs to use variables from the RouteManager instance in order to make its comparisons.agreendev

1 Answers

2
votes

Your best bet would be to define a custom class for a bus stop, instead of storing them as strings and dictionaries.

Make the BusStop class have properties for Name, Location and whatever else. Implement the compareByDistance: method on the BusStop class.

You can still use a dictionary if you need to look them up by name. Just store them with the name as the dictionary's key, and the BusStop object as the dictionary's value.