覆盖Objective-C中的超类方法

时间:2013-09-27 02:44:53

标签: ios objective-c subclass

班级A.h

@protocol ClassADelegate;

@interface ClassA : UIView
    // Some properties

- (void)setupModalView;
@end

@protocol ClassADelegate <NSObject>
    // Some delegate methos
@end

班级A.m

- (void)setupModalView{
    // Some code
}

所以,我创建了我的类“A”的子类,并将其称为“B”。

B.h

@interface ClassB : ClassA

@end

所以,在B.m上,我想要从我的班级“A”中覆盖setupModalView方法。我这样做了:

B.m

- (void)setupModalView{
    NSLog(@"Done.");
}

我认为它应该有效,但事实并非如此。我究竟做错了什么? (澄清一下:我希望B级上的setupModalView做一些与A类setupModalView完全不同的事情。)

编辑:我正在实例化ClassB:

 ClassB *classB = ({
        [[ClassB alloc]initWithNotification:nil]; // Notification is a custom NSObject... nvm
    });

    classB.delegate = self;
    [classB show];

编辑2 :这是我对ClassA的初始化方法:

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
    }
    return self;
}

- (instancetype)initWithNotification:(Notification *)notification{
    self = [super init];
    if (self) {
        self = [[ClassA alloc]initWithFrame:[UIScreen mainScreen].bounds];
        [self configureDetailView];
    }

    return self;
}

- (instancetype)init{
    self = [super init];
    if (self) {
    }
    return self;
}

2 个答案:

答案 0 :(得分:3)

self = [[ClassA alloc]initWithFrame:[UIScreen mainScreen].bounds];

这是错误的。你已经分配了self,现在你明确地将它变成了ClassA的一个实例。如果initWithFrame是您指定的初始化程序,那么当您最初为自己分配内容时,需要调用它而不是[super init]

永远不要在初始化程序中使用显式类名 - 这将使您的类不可分类。

而不是[super init],您需要撰写[self initWithFrame...

答案 1 :(得分:0)

以下是工作示例代码:

#import "AppDelegate.h"

@protocol ClassADelegate;
@interface ClassA : UIView
- (void)setupModalView;
@end
@implementation ClassA
- (void)setupModalView {
    NSLog(@"Super..");
}
@end

@protocol ClassADelegate <NSObject>
- (void)SomeDelegateMethod;
@end

@interface ClassB : ClassA
@end
@implementation ClassB
- (void)setupModalView {
    NSLog(@"Done.");
}
@end

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[ClassB new] setupModalView];
    return YES;
}
@end

NSLog输出
2013-09-26 23:03:12.817测试[41586:a0b]完成。

相关问题