当我期望一个对象时,方法返回null

时间:2014-10-21 20:24:48

标签: objective-c

我在Objective-C中编写了一个名为GameManager的类中的方法。该类有一系列问题声明如下:

@interface GameManager()
   @property(strong, nonatomic)NSMutableArray* questions;
@end

-(id)init{
  if (self == nil){
    self = [[GameManager alloc] init];
    self.questions = [[NSMutableArray alloc] init];
  }
  return self;
}

//The method:
-(Question*)getNextQuestion{

  for (Question* q in _questions)
  {
    NSLog(@"%@",q.answerText);  //Prints out the expected text for each question
  }
  Question* toret = [[Question alloc] init];
  toret = _questions[1];

  NSLog(@"About to return %@", toret.questionText); //prints "About to return (null)"
  return toret;
}

现在从视图控制器调用此方法,该视图控制器将GameManager声明为成员。这是宣言和电话:

@interface QuizController ()
  @property(strong, nonatomic) GameManager* manager;
@end

- (void)viewDidLoad {
   [super viewDidLoad];

   _manager = [[GameManager alloc] init];
   [self.manager setupGame];
   _questions = [[NSMutableArray alloc] init];
   _questions = [_manager getAllQuestions];
}
- (IBAction)nextClicked:(id)sender {
   NSLog(@"Next Clicked");

   if (_manager.nQuestionsAnswered < _manager.nQuestionsInGame){
    _manager.nQuestionsAnswered = _manager.nQuestionsAnswered+1;
    NSLog(@"Number of questions OK");
   }
   Question* next = [[Question alloc] init];
   next = [_manager getNextQuestion];
   if (next == nil)
    NSLog(@"next is nil!");

   NSLog(next.questionText);
   [ self.questionText setText:_questions[_manager.nQuestionsAnswered]];

}

这是问题类,非常简单:

Question.m:     #import&#34; Question.h&#34;

@implementation Question

-(id)init {
if (self == nil){
    self = [[Question alloc] init];
}
return self;
}

-(BOOL) checkAnswer:(NSString *)userAnswer
{
   return [_answerText isEqualToString:userAnswer];
}

@end

Question.h:

#import <Foundation/Foundation.h>

@interface Question : NSObject

@property(strong, nonatomic) NSString *questionText;
@property(strong, nonatomic) NSString *answerText;
@property(strong, nonatomic) NSString *wrong1Text;
@property(strong, nonatomic) NSString *wrong2Text;
@property(strong, nonatomic) NSString *wrong3Text;

- (BOOL) checkAnswer:(NSString*)userAnswer;

@end

我几乎可以肯定我犯了一个我不明白的错误,但是如果有人能说清楚为什么我会从null继续回复getNextQuestion我非常感激!

更新

我在上面添加了一些代码,试图提供更多信息。使用调试器后,我的NSMutableArray _questions实例中的nil似乎是GameManager _manager。我不明白这是怎么回事,所以我已经在initGameManager类中添加了我调用QuizController函数的代码。

1 个答案:

答案 0 :(得分:0)

这两行:

Question* toret = [[Question alloc] init];
toret = _questions[1];

可以浓缩成:

Question* toret = _questions[1];

(请注意,您要获取数组中的第二个对象,而不是第一个对象)

现在,您的NSLog()行在两种情况下将返回nil:

  1. toret.questionText未初始化,
  2. toret为零,如果您的_questions数组只有一个问题,则情况总是如此。
  3. 如果是拼写错误,数组中的索引从0开始,而不是从1开始,所以要获取数组中的第一个对象,请使用:

    Question* toret = _questions[0];
    

    或者

    Question* toret = [_questions firstObject];