Кнопка отображения нулевого выхода - PullRequest
1 голос
/ 12 января 2012

QuestionsViewController.h:

#import <UIKit/UIKit.h>
@interface QuestionsViewController : UIViewController
{    
    int currentQuestionIndex; 
    NSMutableArray *questions; 
    IBOutlet UILabel *questionField; 
}

-(IBAction)showQuestion:(id)sender;
@end

QuestionsViewController.m:

#import "QuestionsViewController.h"

@implementation QuestionsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    self.title = NSLocalizedString(@"First", @"First");
    self.tabBarItem.image = [UIImage imageNamed:@"first"];
}
return self;
}

- (id)init
{
// Call the init method implemented by the superclass
self = [super init];
if (self) {
// Create two new arrays and make the pointers point to them
 questions = [[NSMutableArray alloc] init];

    //Add questions and answers to the array
    [questions addObject:@"Who are you?"];

    [questions addObject:@"Are your talking to me?"];

}
// Return the address of the new object
return self;
}

- (IBAction)showQuestion:(id)sender
{
// Step to the next question
currentQuestionIndex++;

// Am I past the last question?
if (currentQuestionIndex == [questions count]) {
    // Go back to the first question
    currentQuestionIndex = 0;
}

// Gets the string at the index in the questions array
NSString *question = [questions objectAtIndex:currentQuestionIndex];

// Log the string to the console
NSLog(@"displaying question: %@", question);

// Display the string in the question field
[questionField setText:question];
}

// Removed ViewLifeCycle Code

@end

Это сборка и запуск в симуляторе, но когда я нажимаю кнопку showQuestion, я получаю этот вывод:

2012-01-12 11:15:59.180 2Rounds3[1036:f803] displaying question: (null)

Что я делаю не так?

1 Ответ

3 голосов
/ 12 января 2012

Полагаю, вы никогда не вызываете метод -init.

Полагаю, вы создаете свой контроллер вида методом -initWithNibName:bundle. Я прав? Если это так, вы -init метод никогда не вызывается. Поэтому вместо установки переменной экземпляра questions в методе -init сделайте это в вашем основном методе инициализации: -initWithNibName:bundle.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"First", @"First");
        self.tabBarItem.image = [UIImage imageNamed:@"first"];

        // Create two new arrays and make the pointers point to them
        questions = [[NSMutableArray alloc] init];

        //Add questions and answers to the array
        [questions addObject:@"Who are you?"];

        [questions addObject:@"Are your talking to me?"];
    }
    return self;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...