我在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
。我不明白这是怎么回事,所以我已经在init
和GameManager
类中添加了我调用QuizController
函数的代码。
答案 0 :(得分:0)
这两行:
Question* toret = [[Question alloc] init];
toret = _questions[1];
可以浓缩成:
Question* toret = _questions[1];
(请注意,您要获取数组中的第二个对象,而不是第一个对象)
现在,您的NSLog()
行在两种情况下将返回nil:
toret.questionText
未初始化,toret
为零,如果您的_questions
数组只有一个问题,则情况总是如此。如果是拼写错误,数组中的索引从0开始,而不是从1开始,所以要获取数组中的第一个对象,请使用:
Question* toret = _questions[0];
或者
Question* toret = [_questions firstObject];