子类继承超类委托

时间:2020-03-04 23:24:50

标签: objective-c inheritance delegates subclassing

我有一个UIViews层次结构。它们的处理方式不同,但是如果嵌套,则无法触发我的super的setDelegate。我收到崩溃异常[ThirdClass setDelegate:]无法识别的选择器发送到实例。无论我使用SecondClass或ThirdClass是什么(子类),实际上都会发生这种情况,但是如果我使用(FirstClass),则一切正常,但是委托的任何子类均无法识别该调用。我简化了下面的工作,如果我在MainControlInterface中单独调出第一个类,则一切正常。我肯定我在这里做错了事,但无法确定那是什么。如果有人可以帮助您,将不胜感激,谢谢。

  @protocol FirstClassDataSource, FirstClassDelegate;

  @interface FirstClass : UIView
  @property (nonatomic, weak_delegate) __nullable id<FirstClassDataSource> dataSource;
  @property (nonatomic, weak_delegate) __nullable id<FistClassDelegate> delegate;
  @end


  @protocol FirstClassDataSource <NSObject>

  - (NSInteger)doSomething:(FirstClass *)class;

  @optional

  - (NSInteger)doSomethingElse:(FirstClass *)class;

  @end


  @protocol FirstClassDelegate <NSObject>
  @optional
  - (void)handleMoreDelegateMethods:(FirstClass *)class;
  @end



  @implementation FirstClass

  - (void)setDataSource:(id< FirstClassDataSource >)dataSource
   {
    if (_dataSource != dataSource)
    {
       _dataSource = dataSource;
       if (_dataSource)
       {
        [self reloadData];
      }
     }
   }

   - (void)setDelegate:(id< FirstClassDelegate>)delegate
   {
     if (_delegate != delegate)
    {
        _delegate = delegate;
      if (_delegate && _dataSource)
      {
        [self setNeedsLayout];
      }
     }
   }
  @end




  @interface SecondClass : FirstClass 
  -(id)sencondClassesPrivateMethods;
  @end


 @interface ThirdClass : secondClass
 -(id)thirdClassPrivateMethods;
 @end

 @interface MainControlInterface : UIView <FirstClassDataSource, FirstClassDelegate>
 -(ThirdClass *)thirdClass;
 @end

 @implementation MainControlInterface


 -(void)didMoveToSuperview{

 ThirdClass *mythirdSubClass = [self thirdClass];
 mythirdSubClass.delegate = self; 
 mythirdSubClass.dataSource = self; 
 }


 @end

1 个答案:

答案 0 :(得分:1)

我也不知道你在做什么错。但是,您的示例代码将无法编译。 (充满了错别字。)我试图重新创建您在说的内容,并将其进一步简化。 (我使用了CodeRunner,这是一款macOS应用,可简化此类操作。)

#import <Foundation/Foundation.h>

@protocol FirstClassHandling <NSObject>
- (void)doTheThing;
@end

@interface FirstClass : NSObject
@property (nonatomic, weak) id<FirstClassHandling> delegate;
- (void)doSomething;
@end

@implementation FirstClass
- (void)doSomething 
{
    NSLog(@"First class.");
    if ([[self delegate] respondsToSelector:@selector(doTheThing)]) {
        [[self delegate] doTheThing];
    }
}
@end

@interface SecondClass : FirstClass
@end

@implementation SecondClass
- (void)doSomething 
{
    NSLog(@"Second class");
    [super doSomething];
}
@end

@interface Handler : NSObject <FirstClassHandling>
@end 

@implementation Handler 
- (void)doTheThing 
{
    NSLog(@"Doing my thing!!!");
}
@end


int main(int argc, char *argv[]) 
{
    @autoreleasepool {
        Handler* handler = [[Handler alloc] init];
        SecondClass* sc = [[SecondClass alloc] init];
        sc.delegate = handler;
        [sc doSomething];
    }
}

以上内容不会崩溃。请修正您的示例代码。