简体   繁体   English

如何在ViewController中初始化实例变量和属性

[英]How do I initialize instance variables and properties in the ViewController

What is the Syntax for initializing instance variables and propertiesin the ViewController ? 在ViewController中初始化实例变量和属性的语法是什么? this is the code of the implementation 这是实现的代码

CalcViewController.m CalcViewController.m

#import "CalcViewController.h"

@interface CalcViewController ()
{
 int initialValue;
}

@property(nonatomic,weak) BOOl isFirstEntry;

@end


@implementation CalcViewController
@synthesize isFirstEntry = _isFirstEntry;
.......
.......
.......
.......
@end

-(id) init
{
self = [super init];
     if(self)
      {
      ............;
      }
return self;
}

this does not get triggered. 这不会被触发。

If you don't want to do it during a load method, then implement the designated initializer and initialize it there. 如果您不想在加载方法期间执行此操作,请实现指定的初始化程序并在其中初始化它。 If you do not redefine the designated initializer, then you inherit it from your superclass, and you would initialize in the superclass' designated initializer. 如果你没有重新定义指定的初始化程序,那么你从超类继承它,你将在超类的指定初始化程序中初始化。 UIViewController 's designated initializer is: UIViewController的指定初始化程序是:

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle

The init method will be called when you create your object using 使用时创建对象时将调用init方法

CalcViewController *calcView = [CalcViewController alloc] init]; or [CalcViewController new];

If you create the object using some other initiation method it wont be called. 如果使用其他一些启动方法创建对象,则不会调用它。 In a nutshell you will have to remember init is just like any other method. 简而言之,您必须记住init就像任何其他方法一样。

i guess your ViewController is loaded from a nib.. (Xcode project template) try one of the following: 我想你的ViewController是从一个笔尖加载..(Xcode项目模板)尝试下列之一:

- (id)initWithCoder:(NSCoder)aDecoder {
    self = [super initWithCoder:aDecoder];
    if(self) {
        ...
    }
    return self;
}

But be aware that when this method is called all connections from Interface Builder are not set up (parent, children, actions, ...). 但请注意,调用此方法时,未设置Interface Builder的所有连接(父级,子级,操作,...)。 If you want to rely on IB-connections you can use this method: 如果您想依赖IB连接,可以使用以下方法:

- (void)awakeFromNib{
    ...
}

Note that both methods will be called only when loading the ViewController itself from a NIB, not only its view. 请注意,只有从NIB加载ViewController本身时才会调用这两种方法,而不仅仅是视图。 This is usually because XCode gives you a MainWindow.xib that contains a view controller inside (-> NIB). 这通常是因为XCode为您提供了一个MainWindow.xib,其中包含一个视图控制器( - > NIB)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM