views:

69

answers:

2

Example is provided below. If I set

id<RandomProtocol> delegate = [[B alloc] init];

Will doingSomething of class A or class B be called?

A.h

@protocol RandomProtocol

-(NSString*)doingSomething;

@end

@interface A : NSObject <RandomProtocol> 

@end

A.m

#import "A.h"

@implementation A
- (NSString*) doingSomething {
    return @"Hey buddy.";
}
@end

B.h

#import "A.h"

@interface B : A
@end

B.m

#import "B.h"

@implementation B

- (NSString*)doingSomething {
    return @"Hey momma!";
}

@end
A: 

Class B's implementation will be used regardless of whether it follows a protocol or not. The message "doingSomething" is sent to a class of type "B" because that's what you allocated, and in class B, "doingSomething" is the first method encountered by the runtime as it progresses its way up the class hierarchy.

dreamlax
+1  A: 

To be more clear, class B's implementation of -doingSomething will be called rather than class A's implementation, simply because class B inherits from class A, and never calls super's implementation.

If you would want to call A's implementation from inside B's, you would add in the line [super doingSomething] inside B's -doingSomething method.

As mentioned in the previous answer, the fact that -doingSomething is declared in a protocol is completely irrelevant here, as protocols simply exist for providing compile-time information of what a class is capable of doing, for the developer's own benefit.

Steven Degutis