0

我一直在网上浏览一些 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;
}
4

1 回答 1

0

我认为当您使用情节提要时,会调用 initWithCoder 而不是 initWithNibName:bundle:,因此请将数组初始化放在那里。

于 2012-07-26T05:24:25.643 回答