“virtual” method's return type in objective-c

*爱你&永不变心* 提交于 2019-12-06 08:10:24

Take a look at this:

#import <Foundation/Foundation.h>

@interface A : NSObject { }
- (A*) newItem;
- (void) hello;
@end

@interface B : A { int filler; }
- (B*) newItem;
- (void) hello;
- (void) foo;
@end

@implementation A
- (A*) newItem { NSLog(@"A newItem"); return self; }
- (void) hello { NSLog(@"hello from A"); }
@end

@implementation B
- (B*) newItem { NSLog(@"B newItem"); return self; }
- (void) hello { NSLog(@"hello from B: %d", filler); }
- (void) foo { NSLog(@"foo!"); }
@end

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    A *origA = [A new];
    A *myA = [origA newItem];

    NSLog(@"myA: %@", myA);

    B *origB = [B new];
    B *myB = [origB newItem];
    A *myBA = [origB newItem];

    NSLog(@"myB: %@\nmyBA: %@", myB, myBA);

    [origA hello];
    [origB hello];
    [myA hello];
    [myB hello];
    [myBA hello];

    NSLog(@"Covariance?");

    [pool drain];
    return 0;
}

This is rather condensed syntax, and memory management sucks, but you can see that newItem is virtual (sending newItem to myBA returns a B) and covariant, which seems to be what you want.

Note that you could also do:

    B *myAB = (B*)[origA newItem];

but that returns an A, and sending foo to it would tell you that the class does not respond to selector #foo. If you omitted the (B*) cast, you would get a warning about this at compile time.

But ISTM that covariance is no big problem, in Objective-C.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!