我有一个充满问题和答案(带有指定问题)的plist在界面上显示,但我想随机显示问题。请参阅我在下面尝试的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
if (questions && configDictionary) {
for (int i = 0; i < [questions count]; ++i) { int r = (random() % [questions count]); [questions exchangeObjectAtIndex:i withObjectAtIndex:r]; }
[questionLabel setText:[[questions objectAtIndex:currentQuestonIndex] objectForKey:@"question"]];
NSArray *answers = [[questions objectAtIndex:currentQuestonIndex] objectForKey:@"answers"];
[answerLabel0 setText:[answers objectAtIndex:0]];
[answerLabel1 setText:[answers objectAtIndex:1]];
[answerLabel2 setText:[answers objectAtIndex:2]];
[answerLabel3 setText:[answers objectAtIndex:3]];
[pointsPerAnswerLabel setText:[NSString stringWithFormat:@"+%d points", [[configDictionary objectForKey:kPointsPerCorrectAnswer] intValue]]];
[currentQuestionNumberLabel setText:[NSString stringWithFormat:@"question %d", currentQuestonIndex+1]];
}
}
Someone please help?
我收到警告“NSArray'可能无法响应'exchangeObjectAtIndex:withObjectAtIndex:”然后它在尝试运行后崩溃。
请参阅下面的.h文件:
@interface ViewController : UIViewController {
NSDictionary *configDictionary;
NSMutableArray *questions;
int currentQuestonIndex;
NSMutableArray *questionsCorrectlyAnswered;
NSTimer *timer;
int totalTimeLeft;
int currentTimeLeft;
BOOL saveTime;
}
@property (retain, nonatomic) NSMutableArray *questions;
它仍然崩溃。
我在查看之前的表格视图:
- (void)tableView:(UITableView *)_tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
gameViewController = [[QuizViewController alloc] initWithNibName:@"QuizViewController"bundle:nil];
[(QuizViewController*) gameViewController setMasterViewController:self];
[(QuizViewController*) gameViewController setTitle:[[quizzes objectAtIndex:indexPath.row] objectForKey:@"quizName"]];
[(QuizViewController*) gameViewController setQuestions:[[quizzes objectAtIndex:indexPath.row] objectForKey:@"questions"]];
[gameViewController setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self presentModalViewController:gameViewController animated:YES];
}
答案 0 :(得分:1)
无论您在何处设置“questions
”(在代码中未显示),都需要将其设置为“NSMutableArray
”而不是不可变(不可更改,不可交换的)“NSArray
”。
答案 1 :(得分:0)
这是我的捅。不是你的问题的确切答案,但我过去确实做过这样的事情。我做的是我每次启动应用程序时都想要随机化一系列评论。所以这就是我做到的。
NSMutableArray *funnyArray =[[NSMutableArray alloc] initWithObjects:
@"Got Milk?",
@"Got Food?",
@"Life Is Like A Box of Chocolates", nil];
//Randmonize Array
NSUInteger count = [funnyArray count];
for (NSUInteger i = 0; i < count; ++i)
{
// Select a random element between i and end of array to swap with.
int nElements = count - i;
int n = (arc4random() % nElements) + i;
[funnyArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}
现在,在您的情况下,您将仅随机化问题。但是你想要问题和答案对随机化。我不知道你怎么做。也许困难的方法是在你的数组中放一个数字,例如我的牛奶在哪里?当您从数组问题中获得随机str时,您可以删除“1”并在答案数组中查找“1”。我建议使用nsmutablearrays,正如其他人所建议的那样。只需2美分。