shouldn't polymorphism work here?
shouldn't polymorphism work here?
- Subject: shouldn't polymorphism work here?
- From: Conrad Carlen <email@hidden>
- Date: Sun, 27 Mar 2005 22:05:24 -0800
I added a category to NSArray in order to add some binary search functions. Here is my version of STL's lower_bound:
- (id)item keyPath:(NSString*)aKeyPath;
{
unsigned len = [self count];
unsigned first = 0;
unsigned half, middle;
id middleVal;
while (len > 0) {
half = len >> 1;
middle = first + half;
middleVal = [[self objectAtIndex:middle] valueForKeyPath:aKeyPath];
if ([middleVal compare:item] == NSOrderedAscending) {
first = middle;
++first;
len = len - half - 1;
}
else
len = half;
}
return first;
}
It uses key paths so that if the array is full of an object of type "Employee" with and accessor "manager", I can say:
index = [myArray lowerBound:@"fred" keyPath:@"manager.name"] to find the first Employee in my sorted array whose manager's name is fred.
Here's the problem: When compiling this, I get the warnings:
<x-tad-smaller>/Users/<snip>/NSArray+Extensions.m:46: warning: multiple declarations for method `compare:'
/System/Library/Frameworks/Foundation.framework/Headers/NSValue.h:53: warning: using `-(NSComparisonResult)compare:(NSNumber *)otherNumber'
/System/Library/Frameworks/Foundation.framework/Headers/NSDate.h:29: warning: also found `-(NSComparisonResult)compare:(NSDate *)other'
/System/Library/Frameworks/Foundation.framework/Headers/NSString.h:74: warning: also found `-(NSComparisonResult)compare:(NSString *)string'
</x-tad-smaller>Now, as long as these objects implement compare:, shouldn't polymorphism take care of calling the right one? The code does seem to work when the objects being compared are not NSNumbers. Is there anything I can do make it more clear to the compiler and to avoid this warning? If only there was a 'Comparable' formal protocol. Or, should I just trust that the right version of 'compare' will be called depending on the type of objects?
Thanks,
Conrad
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden