iphone - 了解 Objective-C 中的协议(protocol)继承

标签 iphone objective-c inheritance protocols

如果有人能解释协议(protocol)继承背后的逻辑,我将不胜感激。例如以下是什么意思 (UITableView.h):

@protocol UITableViewDelegate<NSObject, UIScrollViewDelegate> 

以下类实现不起作用。我有一个 View1 类(它继承了 UIView),它有一个相关的协议(protocol)。我有另一个类,View2(它继承了 View1)。现在我也想继承协议(protocol)。谁能给我指出正确的方向。

第 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

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

最佳答案

更多地将其视为组合而不是继承。

@protocol UITableViewDelegate<NSObject, UIScrollViewDelegate>定义了一个包含 NSObject 的所有方法的协议(protocol)协议(protocol),UIScrollViewDelegate协议(protocol),以及为 UITableViewDelegate 定义的任何方法协议(protocol)。当您子类化并创建新属性时,您将覆盖父类(super class)属性的类型。为了使这项工作按照我认为的方式进行,您应该声明 View2Delegate作为@protocol View2Delegate <NSObject, View1Delegate> .

关于iphone - 了解 Objective-C 中的协议(protocol)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3751902/

相关文章:

c++ - 无法从模板基类导入 typedef

ruby-on-rails - Ruby on Rails 中的类访问器和继承

iphone - 如何跟踪IOS5中的崩溃?

ios - 解析具有两个子类的抽象 PFObject

iphone - 标签栏应用中的表格 View

objective-c - NSVisualEffectView 上的 NSButton : Wrong Background Color

objective-c - 当应用程序窗口不活动时如何拦截 Cocoa 中的热键

javascript - 如何在 UIWebView 中使用 next 和 Previous 实现查找?

iphone - AVAudioPlayer声音太大

ios - 图片资源和 iOS 手机的问题