2014-08-31 106 views
1

我有一个基类可以说BaseClass它做一些逻辑和处理手势。我有另一个类FooBarClass它提供了视图,也是BaseClass, (FooBar : Base)的子类。从超类发送消息到子类

我知道我可以通过super methodName调用超类中的方法。我现在陷入困境,所有的观点都是这样设计的,现在我需要将消息从FooBar传递到Base

这可能吗?如果是这样如何?我应该使用NSNotifications还是有更好的方法来做到这一点?

+0

通过重写'FooBar'中的方法,您实际上可以将数据返回到父类。就像数据源一样。 – 2014-08-31 11:50:26

+0

@InderKumarRathore我猜如果我没有弄错,OP的询问是相反的。 – GoodSp33d 2014-08-31 12:51:47

回答

0

如果你正在创建子类的实例,你的情况是FooBarClass,你不必担心从超类到子类的消息传递。通过继承,可以从FooBarClass访问头文件(.h)中的任何属性,方法。如果属于BaseClass的方法在FooBarClass中已被覆盖,那么您必须明确地使用super,否则,您可以直接呼叫self。但是,如果属于BaseClass的属性在FooBarClass中被覆盖,那么该变量将保存最后存储的值。这就是为什么通常情况下,属性从未被覆盖的原因,因为它会引起混淆。

最后,不需要NSNotification

例:BaseClass.h

@interface BaseClass : UIView 

- (void)runTest; 
- (void)sayHi; 
- (void)sayHi2; 
@property (assign, nonatomic) NSInteger commonVar; 
@end 

BaseClass.m

- (void)runTest 
{ 
    self.commonVar = 100; 
} 
- (void)sayHi 
{ 
    NSLog(@"Hi from super"); 
    NSLog(@"In super variable = %d", self.commonVar); 
} 
- (void)sayHi2 
{ 
    NSLog(@"Hi from super2"); 
} 

FooBarClass.h

@interface FooBaseClass : BaseClass 

@property (assign, nonatomic) NSInteger commonVar; 
@end 

FooBarClass.m

- (void)runTest 
{ 
    self.commonVar = 1; 
    [super runTest]; // Now, commonVar variable will be holding 100 throughout. 
    [super sayHi]; 
    [super sayHi2]; // Same as next line because there is no sayHi2 overridden. 
    [self sayHi2]; 
    [self sayHi]; 
} 

- (void)sayHi 
{ 
    NSLog(@"Hi from derived"); 
    NSLog(@"In derived variable = %d", self.commonVar); 
} 

希望这个答案能帮助你。