我正在xCode 5上为iOS编写一个问卷调查应用程序。我想创建一系列问题,但问题是每个问题都有不同的答案数量,并且有一些问题,其中有一些正确的答案。
例如:
Q1:天空是......
A1:绿色(错)
A2:蓝色(正确)
Q2:狗是... ...
A1:哺乳动物(正确)
A2:爬行动物(错误)
A3:宠物(正确)
我无法弄清楚如何为此创建数组或数组数组。任何人?
答案 0 :(得分:2)
我知道,每个人都讨厌在Objective-C中编写面向对象的代码,但为什么不使用面向对象的方法呢?
,而不是在Arrays中的Arrays中使用Dictionaries创建适当的类@interface Question : NSObject
@property (copy, nonatomic) NSString *text;
@property (strong, nonatomic) NSArray *answers;
+ (instancetype)questionWithText:(NSString *)text answers:(NSArray *)answer;
@end
@interface Answer : NSObject
@property (copy, nonatomic) NSString *text;
@property (assign, nonatomic, getter = isCorrect) BOOL correct;
+ (instancetype)answerWithText:(NSString *)text isCorrect:(BOOL)correct;
@end
...
Answer *a1 = [Answer answerWithText:@"Mammal" isCorrect:YES];
Answer *a2 = [Answer answerWithText:@"Reprilte" isCorrect:NO];
Answer *a3 = [Answer answerWithText:@"Pet" isCorrect:YES];
Question *q = [Question questionWithText:@"The dog is a..." answers:@[a1, a2, a3]];
答案 1 :(得分:0)
NSArray *mainArray = @[@[@"Q1",@[@[@"A1",@1],@[@"A2",@0],@[@"A3",@0]]],@[@"Q2",@[@[@"A1",@1],@[@"A2",@1],@[@"A3",@0]]]];
所以,上面的mainArray包含整个数据 - >
首先是一系列[问题+答案]
即mainArray的每个对象都包含a question
和corresponding answers array
每个答案数组都包含一个answer and a number
数组,表明其正确与否。
所以,如果number bool value
为1,则表示正确答案,否则如果为零则表示错误答案。
因此,对于您的情况,它将是
NSArray *mainArray = @[@[@"The sky is...",@[@[@"Green",@0],@[@"Blue",@1]]],@[@"The dog is a...",@[@[@"Mammal",@1],@[@"Reptile",@0],@[@"Pet",@1]]]];
//to get first question
NSString *question1 = mainArray[0][0];
NSArray *answerArrayForQuestion1 = mainArray[0][1];
//lets assume user selects answer as 2
//so to check whether its correct or not
NSInteger selectedAnswer=2;
BOOL correct=((NSNumber *)answerArrayForQuestion1[selectedAnswer-1][1]).boolValue; // which logs YES