2013-05-18 29 views
0

超類Resource如何訪問超類的變量在init方法

@interface Resource : CoderObject 

@property (strong, nonatomic) NSString *resourceID; 
@property (assign, nonatomic) ResourceType resourceType; 
@property (assign, nonatomic) DataType dataType; 

@end 

子類ViewResource

@interface ViewResource : Resource 

@property (strong, nonatomic) CustomView *view; 
@property (strong, nonatomic) UIViewController *viewController; 

@end 

在子類ViewResourceinit方法如何訪問Resource的變量dataType?現在我試圖只用super.dataType = ...

還有其他方法嗎?

回答

2

你只需要使用self.dataType。您的子類完全可見所有在.h文件中定義的超類屬性。使用self.xxx還可以在未來需要時覆蓋訪問方法,而無需重新編輯所有使用代碼。

看看你的鏈接,足夠公平。這些都是有效的點。訪問者不應該有副作用,但你不能保證他們不會。如果屬性定義的超類,那麼你有兩個選擇:

  1. 使用self.xxx設置屬性,並努力確保無副作用
  2. 呼籲超級的init方法,傳遞所需的參數,並設定他們那裏
+0

但是我聽說你不應該在'init'方法中調用'self.method'? – sunkehappy

+1

給出了什麼理由?最好使用訪問器方法來設置值。你不應該使用訪問器的唯一時間是當你在訪問器中時。 – Wain

+0

選中此鏈接:http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210-CH5-SW11 – sunkehappy

0

北斗星他回答說你有你的超類的類成員的直接訪問(如果他們不是私有的)。

而且是沒有問題的init方法調用self.property只要你的初始化看起來像這樣

-(id)initAndTheNameYoWantAndMaybeSomeParameters:(NSString *)paramExample { 
    self = [super initNameOfAnInitMethodFromSuperClass]; 
    //check if the init was with success 
    if(self != nil) { 
     self.myStringProp = paramExample; 
     //or 
     self.propertyFromSuper = paramExample; 
    } 
} 

是的,你也可以做愚蠢的東西在initMethods(我以前做過:)))比如從裏面調用相同的initMethod,它會產生遞歸調用,導致應用程序崩潰。 (容易發現這個問題)