2015-01-21 69 views
0

我有一個UIViewController控制Xcode中的幾個不同的視圖。我想使用當前視圖中的信息在傳入視圖上設置標籤。我知道標籤和其他UI元素在視圖加載時會重置,但我的非UI @property也被設置爲零。在同一viewController中加載另一個視圖清除非UI屬性

這裏是我的財產:

@property (strong, nonatomic) NSString* username; 

這裏是設置它的代碼:

//NSLog(@"%@",dict); 
if ([dict[@"login"] intValue]){ 
    [self performSegueWithIdentifier:@"JoinSuccess" sender:sender]; 
    self.username = dict[@"user"]; 

下面是試圖使用它的代碼:

- (void)viewDidLoad { 
[super viewDidLoad]; 
NSLog(@"%@", self.username); 
self.welcomeLabel.text = [NSString stringWithFormat:@"Welcome, %@",self.username]; 
} 

我我試過之前和之後performSegueWithIdentifier,但無論如何,當我嘗試t o在viewDidLoad中引用它的值爲零。任何想法爲什麼它正在重設我的@property?我的猜測可能是它創建了我的viewController的新實例。如果是這樣的話,我怎麼能通過所需的變量?

+0

當第一次訪問UIViewController的視圖屬性時,會調用'viewDidLoad'。 – KudoCC 2015-01-21 06:18:01

+0

將用戶名分配給viewDidload中的另一個字符串它將解決您的問題 – Sam 2015-01-21 06:30:09

回答

0

正如你所說,當你調用performSegueWithIdentifier時,viewController將被重新創建。您可以在新實例中設置值。你可以這樣做

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    YourViewController *vc = [segue destinationViewController]; 
    vc.username = dict[@"user"]; 
} 
+0

感謝您的回覆! 'dict'是一個局部變量,有沒有什麼辦法可以在方法中設置它? – 2015-01-21 06:31:17

+0

如果您正在使用'performSegue'進行轉換,則沒有其他辦法,您應該在'prepareForSegue'中設置此屬性,僅將'dict'作爲屬性以將其轉換到此處。 – 2015-01-21 06:37:59

+0

這對我有用: ' - (void)prepareForSegue :(UIStoryboardSegue *)segue發件人:(id)發件人 { { LoginViewController * new = [segue destinationViewController]; new.username = self.username; }' 感謝您的幫助! – 2015-01-21 06:43:40

0

你必須添加另一種方法來將值從一個視圖控制器傳遞到另一個視圖控制器。

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    nextViewcontroller *nextViewcontrollerObjt = [segue 
destinationViewController]; 
// apply setter to set value of next view 
    nextViewcontrollerobject.title = nextViewControllerTitleString; 
    nextViewcontrollerobject.variable_1= currentView_variable1; 
    nextViewcontrollerobject.variable_2 =currentView_variable2; 
     } 
相關問題