2011-06-27 49 views
0

我有一類,「DogViewController」,在這裏我聲明屬性和合成它:在另一個類中設置對象?

@property (nonatomic, assign) NSInteger myInt; 

@synthesize myInt; 

我有另一個類,"CatViewController",其中我想設置的敏可變的,所以這是我做過什麼:

@property (nonatomic, retain) DogViewController *myDogViewController; 

@synthesize myDogViewController; 

myDogViewController.myInt = 5; 

然後,我想從DogViewController類,這是我做的訪問敏:

someVar = self.myInt; 

someVar應b該命令之後的e == 5。

有沒有原因,爲什麼不行?

+0

您是否在myDogViewController.myInt = 5時實例化了'myDogViewController'? –

+0

@property命令是否實例化它? – Andrew

+0

@property指令只是指示Objective-C預編譯器準備在實現文件中創建getter和setter。 @synthesize關鍵字然後使預編譯器注入實際的getter/setter代碼(除非手動覆蓋這些方法)。如果您的屬性需要初始化,您需要單獨執行(例如,在構造函數中)。 – Perception

回答

1

您必須先實例化DogViewController。因此,在CatViewController:

DogViewController *dogViewController = [[DogViewController alloc] [email protected]"DogViewController" bundle:nil]; 
dogViewController.myInt = 5; 
// If you are using a navigation controller push DogViewController like this: 
[self.navigationController pushViewController:dogViewController animated:YES]; 
[dogViewController release]; 

如果你不使用導航控制器,只顯示你想要

+0

你能否編輯你的答案以反映OP可能沒有使用視圖控制器的事實? – Perception

+0

當然 - 但這不是討論VC的問題嗎? – darksky

+0

根據OP今天在SO上的其他問題,這些不是VC的。Ofc,他在這個問題中從來沒有說過他們 - 總是可以安全地採取最低的共同標準。 – Perception

-1

任何方式,我想你不會得到值爲5,因爲它將被重置了這一觀點。

你可以像下面這樣做。

你的 「CatViewController」 中,創建一個像 「的setParent」

拿在.h文件中變量的一種方法:

ID父母;

功能.m文件:在CatViewController.m文件

-(void)setParent:(id)pidParent{ 
parent = pidParent; 
} 

進口 「DogViewController.h」。

當您推送到DogViewController時,也稱爲它的setParent方法。

Like [objDogViewController setParent:self];

那麼你可以通過使用「父」變量來設置值。

乾杯。

+1

這不是他的問題的原因。他的例子中的DogViewController永遠不會被初始化,這就是爲什麼他無法訪問它的任何屬性。 – Perception

0

嘗試使用不使用retain而使用基本數據類型使用assign

@property (nonatomic, assign) NSInteger myInt; 
相關問題