On Oct 14, 2008, at 7:11 AM, Chris Suter wrote:

You can't override the type for existing methods. For example,
initWithString: always returns an id. You can define them as returning
something different but the compiler will ignore it.

Just a clarification on this particular point- it is possible to override the type(s) of existing methods, both the argument and return types. The following snippet of code demonstrates this. The return types were specifically chosen because the ABI specifies that each result is returned in a different way from the other (i.e., the double is returned via a floating point register, at least on ppc).

#import <Foundation/Foundation.h>

@interface MYTest        : NSObject -(int)    result; @end
@interface MYMutableTest : MYTest   -(double) result; @end
@interface MYOtherTest   : NSObject -(NSRange)result; @end

@implementation MYTest -(int) result { return(23); } @end @implementation MYMutableTest -(double) result { return(42.0); } @end @implementation MYOtherTest -(NSRange)result { return(NSMakeRange(23,42)); } @end

int main(int argc, char *argv[]) {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

MYTest *myTest = [[[MYTest alloc] init] autorelease]; MYMutableTest *myMutableTest = [[[MYMutableTest alloc] init] autorelease]; MYOtherTest *myOtherTest = [[[MYOtherTest alloc] init] autorelease];

  NSLog(@"myTest       : %d", [myTest result]);
  NSLog(@"myMutableTest: %f", [myMutableTest result]);
  NSLog(@"myOtherTest  : %@", NSStringFromRange([myOtherTest result]));

  return(0);
}

shell% gcc -o typeTest typeTest.m -framework Foundation
[No warnings or errors]
shell% ./typeTest
2008-10-15 05:34:48.566 typeTest[7494:807] myTest       : 23
2008-10-15 05:34:48.625 typeTest[7494:807] myMutableTest: 42.000000
2008-10-15 05:34:48.645 typeTest[7494:807] myOtherTest  : {23, 42}

This demonstrates that the correct return type was chosen at compile time because each result type is returned in a unique and different way, If the compiler didn't get the return type correct, the results would be random garbage. The compiler can do this because the class is statically typed. If the class isn't known (i.e., id), then things don't work quite so well, especially in the example above. Trying to get a floating point double result out of a general purpose int register usually doesn't work. :)

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to