在iOS应用加载时使用对象初始化数组

时间:2012-07-26 05:09:34

标签: ios xcode viewdidload

我一直在网上浏览一些iOS示例我遇到了一个应用程序,其中应用程序初始化一个数组,然后在iOS应用程序启动时向其添加对象。我在我的实现文件中使用(void) viewDidLoad时初始化工作但是当我使用

时初始化数组不起作用

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

有人可以告诉我为什么会这样吗?谢谢!

这是代码 -

(void) viewDidLoad
{
if (self) {
    questions = [[NSMutableArray alloc] init];
    answers = [[NSMutableArray alloc] init];

    // Add objects to the arrays
    [questions addObject:@"What is 1+1"];
    [answers addObject:@"2"];

    [questions addObject:@"What is 2+2"];
    [answers addObject:@"4"];

    [questions addObject:@"What is 3+3"];
    [answers addObject:@"6"];
}

[super viewDidLoad];

和initWithNibName的代码

 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {

    // Create two arrays and make the pointers point to them
    questions = [NSMutableArray array];
    answers = [NSMutableArray array];

    // Add questions and answers to the arrays
    [questions addObject:@"From what is cognac made?"];
    [answers addObject:@"Grapes"];

    [questions addObject:@"What is 7 + 7?"];
    [answers addObject:@"14"];

    [questions addObject:@"What is the capital of Vermont?"];
    [answers addObject:@"Montpelier"];

}
return self;
}

1 个答案:

答案 0 :(得分:0)

我认为当你使用故事板时,调用initWithCoder而不是initWithNibName:bundle:,所以把数组初始化放在那里。