【问题标题】:viewdidload issue xcode 4.2viewdidload 问题 xcode 4.2
【发布时间】:2012-05-26 16:22:12
【问题描述】:

我刚刚学习了如何通过推送和弹出来更改视图之间的切换。 现在,在我的第二个视图中,我添加了一个标签,每次我的第二个视图是 push 时,我都想改变她的值。 我添加标签,将她连接到我的文件所有者,然后使用 viewdidload 更改她的值。 当我进入第二个视图时,什么都没有发生。但是当我使用 viewdidapper 时,一切都很完美(但标签值更新需要一秒钟)。

我的代码是: mysecondviewcontroller.h:

@interface SecondViewController : UIViewController
{
     IBOutlet UILabel *textLabel;
     NSString *label;
}

@property (copy) NSString *label;

@end

mysecondviewcontroller.m(当然我合成标签):

-(void)viewDidAppear:(BOOL)animated
 {
   textLabel.text = label;
   NSLog(@"viewdidapper2");
 }

 - (void)viewDidLoad
{
   textLabel.text = label;
   [super viewDidLoad];
    NSLog(@"viewdidload2");

// Do any additional setup after loading the view from its nib.
}

我的 firstviewcontroller.m(IBAction):

- (IBAction)pushViewController:(id)sender
{
    static int count = 1;

    SecondViewController *secondVieController = [[SecondViewController alloc] init];
    [self.navigationController pushViewController:secondVieController animated:YES];   
   secondVieController.title = @"second";
   secondVieController.label = [NSString stringWithFormat:@"number: %d", count];     

   count++;

}

我的 viewdidload 有什么问题?

谢谢!

【问题讨论】:

    标签: objective-c xcode4 viewcontroller viewdidload viewwillappear


    【解决方案1】:

    如果您使用的是viewDidLoad,则需要在执行任何其他操作之前调用超级函数。

    - (void)viewDidLoad
    {
       [super viewDidLoad];
       textLabel.text = label;
        NSLog(@"viewdidload2");
    
    // Do any additional setup after loading the view from its nib.
    }
    

    我认为还有另一个问题,您在推送视图控制器后设置secondVieController.label,但这意味着在viewDidLoad 运行时,secondVieController.label 仍然为空。这应该可以解决它。

    - (IBAction)pushViewController:(id)sender
    {
        static int count = 1;
    
        SecondViewController *secondVieController = [[SecondViewController alloc] init];
        secondVieController.title = @"second";
        secondVieController.label = [NSString stringWithFormat:@"number: %d", count];     
        [self.navigationController pushViewController:secondVieController animated:YES];   
    
        count++;
    
    }
    

    【讨论】:

    • 事实上,几乎所有你重写的函数都是如此。不过也有例外,尤其是当您不使用 ARC 时的 dealloc 函数,超级函数是您调用的最后一件事。
    • 我喜欢这样想——在“进入”的过程中首先调用 super - init、viewWillAppear 等,然后在退出的过程中最后调用它 - dealloc、viewWillDisappear。
    【解决方案2】:

    如果您想在每次加载视图时更新标签,那么您必须将代码写入 Viewwillappear 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-18
      • 1970-01-01
      • 2012-01-17
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      • 1970-01-01
      • 2012-05-14
      相关资源
      最近更新 更多