【问题标题】:Button displaying Null output显示 Null 输出的按钮
【发布时间】:2012-01-12 16:31:11
【问题描述】:

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)

我做错了什么?

【问题讨论】:

  • 尝试在 action 方法中记录你的数组,看看那里有什么?

标签: iphone objective-c ios


【解决方案1】:

我猜你永远不会调用-init 方法。

我想您正在使用 -initWithNibName:bundle 方法创建视图控制器。我对么?如果是这样,您的 -init 方法永远不会被调用。因此,不要在-init 方法中设置实例变量questions,而是在您的主要初始化方法中进行:-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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    相关资源
    最近更新 更多