2014-08-31 67 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); 
} 

希望這個答案能幫助你。