假设您有 5 个问题,每个问题最多可以有 5 个选项。
您有一个带有表格视图的屏幕,您一次在表格视图中显示 1 个带有选项(2 - 5 行)的问题,您可以选择让用户导航到下一个问题(在这种情况下,您用下一个问题重新加载表格)
这是你的设置。
现在,根据我的建议,创建一个 NSObject 类来保存每个问题的选定选项的信息。
@interface CustomObject : NSObject
{
NSInteger _questionId;
NSInteger _answerId;
}
@property (nonatomic,readwrite,assign) NSInteger questionId;
@property (nonatomic,readwrite,assign) NSInteger answerId;
@end
#import "CustomObject.h”
@implementation CustomObject
@synthesize questionId = _questionId, answerId = _answerId;
-(id) initWithQuestionId:(NSUInteger)qId answerId:(NSUInteger)aId
{
if( (self=[super init]) ) {
_questionId = qId;
_answerId = aId;
}
return self;
}
@end
现在假设对于 5 个问题,您将 id’s 设为 1, 2, 3, 4, 5 并且最初没有选择任何答案,因此将 selected answer id 的不适用 id 保留为 -1。
在你的类中创建一个NSMutableArray,将表格视图显示为
NSMutableArray *m_selectedAnsInfoList;
将上面的数组初始化一次
m_selectedAnsInfoList = [NSMuatbleArray alloc] init];
最初为每个问题创建 CustomObject 类的对象
(假设我们有5 question 所以questionCount = 5)
for (int i=1; i <= questionCount : i++)// will iterate for 5 times
{
//create instance of CustomObject with current iteration count as question id and
// initially -1 for answer id, as for the first time no answer will be selected
CustomObject *obj = [[CustomObject alloc] initWithQuestionId:i answerId:-1];
// add object to the array
[m_selectedAnsInfoList addObject:obj];
[obj release];
}
您创建的表格视图将答案显示为问题的行,最初您会将所有行显示为未选中。
在didSelectRowAtIndexPath内:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// currentQuestionId keeps id of the table view showing current question
// using which access the questionInfoObject
obj = [m_selectedAnsInfoList objectAtIndex:currentQuestionId];
// set answer id in object
obj.answerId = indexPath.row; (from 0 to (number of answers - 1));
// replace old object with updated obj in array as
[m_selectedAnsInfoList replaceObject:obj atIndex:currentQuestionId];
}
通过这种方式,您可以存储为每个问题选择的答案的信息,并根据列表中相应对象中存储的信息显示它们选择的答案。