12

I'll appreciate if anyone can explain the logic behind protocol inheritance. e.g. what does the following mean (UITableView.h):

@protocol UITableViewDelegate<NSObject, UIScrollViewDelegate> 

The following class implementation doesn't work. I have a class View1 (which inherits UIView), with an associated protocol. I have another class, View2 (which inhertits View1). Now i want to inherit the the protocol as well. Can anyone please point me in the right direction.

Class 1:

@protocol View1Delegate;

@interface View1 : UIView {
    id <View1Delegate> delegate;
    // . . .
}

@property (nonatomic, assign) id <View1Delegate> delegate; // default nil. weak reference

@end

@protocol View1Delegate <NSObject>
- (void)View1DelegateMethod;
@end

@implementation View1

@synthesize delegate;

// . . .
@end

Class 2:

@protocol View2Delegate;

@interface View2 : View1 {
    id <View2Delegate> delegate;
    // . . .
}

@property (nonatomic, assign) id <View2Delegate> delegate; // default nil. weak reference

@end

@protocol View2Delegate <NSObject>
- (void)View2DelegateMethod;
@end

@implementation View2

@synthesize delegate;

// . . .
@end

2 Answers 2

12

Think of it more as composition rather than inheritance.

@protocol UITableViewDelegate<NSObject, UIScrollViewDelegate> defines a protocol that includes all the methods of the NSObject protocol, the UIScrollViewDelegate protocol, as well as any methods defined for the UITableViewDelegate protocol. When you subclass and create a new property, you're overriding the type of the superclasses property. To make this work how I think you want, you should declare View2Delegate as @protocol View2Delegate <NSObject, View1Delegate>.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your reply. I'm declaring the protocol as you've mentioned, but the problem i'm facing is with the declaration of id <...>delegate; In View1, I have id <View1Delegate> delegate; with it's associated @property and @synthesize. Since i'm inheriting View1 in View2, when i declare id <View2Delegate> delagete; with it's associated @property and @synthesize, i get an error: "Property 'delegate' attempting to use ivar 'delegate' declared in super class of 'View2'. What's the correct way to handle this situation. Please see the sample classes i've posted above.
0

It's exactly the same as the inheritance of interfaces in Java (interface UITableViewDelegate extends NSObject, UIScrollViewDelegate), C# (interface UITableViewDelegate : NSObject, UIScrollViewDelegate), etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.